I am trying to make a program that will randomly show the outputs of a coin flipping until there are 5 heads in a row and then the program has to stop. I do not have a lot of experience coding so any help is appreciated!
So far all I have is a program that outputs the result of a coin flip one time.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(NULL));
int flip = (rand()%2)+ 1 ;
cout<<coin;
return 0;
}
Use something like this - a while loop. This kind of loop will continue to run while the condition in the parentheses is True. Once it is False it will break out of the loop.
This may not be exactly what works for you but this is the basic outline of the logic behind what you are trying to achieve.
Feel free to comment below if you have more questions.
int numberOfHeads = 0;
while (numberOfHeads <= 5) {
flipCoin(); // or whatever method is used to call a coin flip -- you can replace this line with whatever logic works best for you
if (coinIsHeads == true) { // again you may need to change the logic in the parentheses for however you wish to test for a head.
numberOfHeads++;
}
}
Since this looks like homework, and it should be a way for you to learn, I will not code it for you. But, I shall rather provide you some direction.
Create an integer variable that holds the count value. What I mean by that is you have to keep count of how many times you have heads.
Read up on conditional statements, in this case a while loop would be wise, and the arguments associated to the while should be the counter and its relation to the value 5.
Assign a value for heads and tails, right now you don't know what the int flip results in. Maybe have it so that even numbers are head and odd numbers are tails. You gets these even and odd values from your flip.
Again, this should be a very simple program to write. I would highly encourage you to use your time to read your textbook (or find a beginners C/C++ book online) and understand datatypes, conditionals, compiling, ect...
Related
This is a very simple question, but unfortunately, I am stuck and do not know what to do. My program is a simple program that keeps on accepting 3 numbers and outputs the largest of the 3. The program keeps on running until the user inputs a character.
As the tittle says, my question is how I can make this execute faster ( There will be a large amount of input data ). Any sort of help which may include using a different algorithm or using different functions or changing the entire code is accepted.
I'm not very experienced in C++ Standard, and thus do not know about all the different functions available in the different libraries, so please do explain your reasons and if you're too busy, at least try and provide a link.
Here is my code
#include<stdio.h>
int main()
{
int a,b,c;
while(scanf("%d %d %d",&a,&b,&c))
{
if(a>=b && a>=c)
printf("%d\n",a);
else if(b>=a && b>=c)
printf("%d\n",b);
else
printf("%d\n",c);
}
return 0;
}
It's working is very simple. The while loop will continue to execute until the user inputs a character. As I've explained earlier, the program accepts 3 numbers and outputs the largest. There is no other part of this code, this is all. I've tried to explain it as much as I can. If you need anything more from my side, please ask, ( I'll try as much as I can ).
I am compiling on an internet platform using CPP 4.9.2 ( That's what is said over there )
Any sort of help will be highly appreciated. Thanks in advance
EDIT
The input is made by a computer, so there is no delay in input.
Also, I will accept answers in c and c++.
UPDATE
I would also like to ask if there are any general library functions or algorithms, or any other sort of advise ( certain things we must do and what we must not do ) to follow to speed up execution ( Not just for this code, but in general ). Any help would be appreciated. ( and sorry for asking such an awkward question without giving any reference material )
Your "algorithm" is very simple and I would write it with the use of the max() function, just because it is better style.
But anyway...
What will take the most time is the scanf. This is your bottleneck. You should write your own read function which reads a huge block with fread and processes it. You may consider doing this asynchronously - but I wouldn't recommend this as a first step (some async implementations are indeed slower than the synchronous implementations).
So basically you do the following:
Read a huge block from file into memory (this is disk IO, so this is the bottleneck)
Parse that block and find your three integers (watch out for the block borders! the first two integers may lie within one block and the third lies in the next - or the block border splits your integer in the middle, so let your parser just catch those things)
Do your comparisions - that runs as hell compared to the disk IO, so no need to improve that
Unless you have a guarantee that the three input numbers are all different, I'd worry about making the program get the correct output. As noted, there's almost nothing to speed up, other than input and output buffering, and maybe speeding up decimal conversions by using custom parsing and formatting code, instead of the general-purpose scanf and printf.
Right now if you receive input values a=5, b=5, c=1, your code will report that 1 is the largest of those three values. Change the > comparisons to >= to fix that.
You can minimize the number of comparisons by remembering previous results. You can do this with:
int d;
if (a >= b)
if (a >= c)
d = a;
else
d = c;
else
if (b >= c)
d = b;
else
d = c;
[then output d as your maximum]
That does exactly 2 comparisons to find a value for d as max(a,b,c).
Your code uses at least two and maybe up to 4.
I solved a programming puzzle using a brute force method and without dynamic programming, and it worked fine. Here is the puzzle:
An orienteering map is to be given in the following format.
" ##### "
" #...# "
" #S#G# "
" ##### "
Calculate the minimum distance from the start to the goal with passing all the checkpoints.
A map consists of 5 characters as following. You can assume that the map does not contain any invalid characters and the map has exactly one start symbol 'S' and exactly one goal symbol 'G'.
'S' means the orienteering start.
'G' means the orienteering goal.
'#' means an orienteering checkpoint.
'.' means an opened-block that players can pass.
'#' means a closed-block that players cannot pass.
It is allowed to move only by one step vertically or horizontally (up, down, left, or right) to the next block. Other types of movements, such as moving diagonally (left up, right up, left down and right down) and skipping one or more blocks, are NOT permitted.
You MUST NOT get out of the map.
Distance is to be defined as the number of movements to the different blocks.
You CAN pass opened-blocks, checkpoints, the start, and the goal more than once if necessary.
You can assume that parameters satisfy following conditions.
1 <= width <= 100
1 <= height <= 100
The maximum number of checkpoints is 18.
Then I found a much faster solution, which I don't understand some things about:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<cstring>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<cstdlib>
#include<ctime>
#include<set>
#include<math.h>
using namespace std;
typedef long long LL;
const int maxn = 1e2+ 10;
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define pb push_back
std::vector<int>path;
const int INF=1<<20;
struct Point
{
int x,y;
bool operator < (const Point &a)const
{
return x<a.x||(x==a.x)&&y<a.y;
}
};
std::vector<Point>P;
char mat[maxn][maxn];
int vis[maxn][maxn];
int w,h,s,e;
int d[1<<20][20];
int dx[]={-1,0,0,1};
int dy[]={0,-1,1,0};
int dist[25][25];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
while(cin>>w>>h){
map<Point,int>id;
P.clear();
path.clear();
memset(d,100,sizeof d);
memset(dist,100,sizeof dist);
for(int i=0;i<h;i++){
scanf("%s",mat[i]);
for(int j=0;mat[i][j];++j){
char &c=mat[i][j];
if(c=='S'||c=='G'||c=='#'){
P.pb((Point){i,j});
int sz=P.size();
id[P[sz-1]]=sz;
if(c=='S')s=sz-1;
else if(c=='G')e=sz-1;
path.pb(sz-1);
}
}
}
for(int i=0;i<path.size();i++){
Point now=P[path[i]];
int x=path[i];
//out<<"x "<<x<<endl;
dist[x][x]=0;
memset(vis,0,sizeof vis);
vis[now.x][now.y]=1;
queue<Point>q;
q.push(now);
//cout<<"Bfs"<<endl;
while(!q.empty()){
now=q.front();q.pop();
for(int i=0;i<4;i++){
int nx=now.x+dx[i],ny=now.y+dy[i];
if(nx>=0&&nx<h&&ny>=0&&ny<w&&mat[nx][ny]!='#'&&!vis[nx][ny]){
Point tp=(Point){nx,ny};
q.push(tp);
vis[nx][ny]=vis[now.x][now.y]+1;
if(id[tp]){
dist[x][id[tp]-1]=vis[now.x][now.y];
}
}
}
}
}
d[1<<s][s]=0;
int M=path.size();
for(int i=0;i<(1<<M);++i){
for(int j=0;j<M;j++){
int p=path[j];
for(int k=0;1<<k<=i;k++){
if(i&(1<<k)){
d[i|(1<<p)][p]=min(d[i|(1<<p)][p],d[i][k]+dist[k][p]);
}
}
}
}
cout<<d[(1<<M)-1][e]<<endl;
}
return 0;
}
Here are 3 specific questions I have about it:
What is the use of the constant INF? It isn’t used anywhere in the program. I understand that programmers very often leave some things in their programs which may not seem to be of any use presently, but would be useful for any future modifications. Does INF serve that same purpose? If any kind of modification is performed to make the program more efficient or to use a different method, INF is used?
The use of the left-shift operator inside the array dimensions. For example, int d[1<<20][20]. What purpose does the let-shift operator accomplish with regard to this program? There are various other instances where the let shift operator has been used inside array dimensions, and I can’t understand why.
The overloading of the less-than operator. In the Point structure, the less-than operator is overloaded. But I can't seem to find out where in the program it has been called. It needs a Point object to call it, but I can’t find any place where any Point object calls that member function.
Your questions aren't invalid, but do not need all the context to ask them. They could each be separate questions, and I've provided a link for each showing that the essence of the question has been asked before more succinctly. If you isolate your questions and separate them out of the specific body of code you are looking at, that's better--they can be triaged more easily as duplicates.
What is the use of the constant INF?It isn’t used anywhere in the program. I understand that programmers very often leave some things in their programs which may not seem to be of any use presently, but would be useful for any future modifications. Does INF serve that same purpose? If any kind of modification is performed to make the program more efficient or to use a different method, INF is used?
If you delete the line declaring INF, does it still compile and work? Does it get slower? If so, it is a magic incantation that makes programs faster, known only in C++ secret societies. :-) If not, it's just a leftover definition as you suspect...perhaps used at some time, or perhaps never was.
See:
How do I detect unused macro definitions & typedefs?
The use of the left-shift operator inside the array dimensions. For example, int d[1<<20][20]. What purpose does the let-shift operator accomplish with regard to this program? There are various other instances where the let shift operator has been used inside array dimensions, and I can’t understand why.
In binary math, shifting 1 some number of bits left is the same as raising 2 to that power. So 1 << 20 is 2^20, or 1048576. It's faster to bit shift than to call a power function, although with an optimized enough power function that can special case when the base is 2...how much faster may not be that much:
are 2^n exponent calculations really less efficient than bit-shifts?
The overloading of the less-than operator. In the Point structure, the less-than operator is overloaded. But I can’t seem to find out where in the program it has been called. It needs a Point object to call it, but I can’t find any place where any Point object calls that member function.
One might think that if you want to test if a method is ever called or a definition used, you can delete it and see if it still compiles. But in C++ that doesn't always work; some definitions are overloads. If you delete them, the program still compiles but just falls through to more basic behavior. Even preprocessor macros can be funny because one file might detect if it had been defined elsewhere, and do something different if not...
There are other approaches, like just throwing an exception or asserting if it's ever called in the course of running. People offer some other thoughts here:
Find out if a function is called within a C++ project?
As #BrianSchlenker points out, the less than operator is definitely used despite the lack of explicit calls in the code shown. It's used to order the elements of map<Point,int> id;. The C++ std::map type imposes ordering on its contents, and defaults to using operator< to achieve this ordering...though you may override this. If you print something out inside the less than function, you'll see it called every time the id map is interacted with.
(Note: If you want an unordered map you have to use std::unordered_map, but that requires your datatype to have a different ability to calculate its std::hash...as well as a test for equality.)
In general: this code is not stylized in a maintainable or readable manner. I'd suggest that if you want to learn methods for increasing C++ program performance, you avoid the tarpit of reading any piece of obfuscated code you find...just because it happened to catch your attention.
Can you learn from it? I guess, but de-obfuscating it and commenting it will be your first step. Not a great idea, especially if you have to go asking others to help you do it, because even if they know how...they probably don't want to. Better would be to work through steps to improve your own implementation in a stable logical way, where you don't step too far outside of your sphere of understanding in any one step.
(Though if you can find the original author of such things, you might be able to engage them in a conversation about it and comment it for you. If they don't have the interest, why would random people on the Internet?)
First a little introduction:
I'm a novice C++ programmer (I'm new to programming) writing a little multiplication tables practising program. The project started as a small program to teach myself the basics of programming and I keep adding new features as I learn more and more about programming. At first it just had basics like ask for input, loops and if-else statements. But now it uses vectors, read and writes to files, creates a directory etc.
You can see the code here: Project on Bitbucket
My program now is going to have 2 modes: practise a single multiplication table that the user can choose himself or practise all multiplication tables mixed. Now both modes work quite different internally. And I developed the mixed mode as a separate program, as would ease the development, I could just focus on writing the code itself instead of also bothering how I will integrate it in the existing code.
Below the code of the currently separate mixed mode program:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;
using std::string;
int newquestion(vector<int> remaining_multiplication_tables, vector<int> multiplication_tables, int table_selecter){
cout << remaining_multiplication_tables[table_selecter] << " * " << multiplication_tables[remaining_multiplication_tables[table_selecter]-1]<< " =" << "\n";
return remaining_multiplication_tables[table_selecter] * multiplication_tables[remaining_multiplication_tables[table_selecter]-1];
}
int main(){
int usersanswer_int;
int cpu_answer;
int table_selecter;
string usersanswer;
vector<int> remaining_multiplication_tables = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> multiplication_tables(10, 1);//fill vector with 10 elements that contain the value '1'. This vector will store the "progress" of each multiplication_table.
srand(time(0));
table_selecter = rand() % remaining_multiplication_tables.size();
cpu_answer = newquestion(remaining_multiplication_tables, multiplication_tables, table_selecter);
while(remaining_multiplication_tables.size() != 0){
getline(cin, usersanswer);
stringstream usersanswer_stream(usersanswer);
usersanswer_stream >> usersanswer_int;
if(usersanswer_int == cpu_answer){
cout << "Your answer is correct! :)" << "\n";
if(multiplication_tables[remaining_multiplication_tables[table_selecter]-1] == 10){
remaining_multiplication_tables.erase(remaining_multiplication_tables.begin() + table_selecter);
}
else{
multiplication_tables[remaining_multiplication_tables[table_selecter]-1] +=1;
}
if (remaining_multiplication_tables.size() != 0){
table_selecter = rand() % remaining_multiplication_tables.size();
cpu_answer = newquestion(remaining_multiplication_tables, multiplication_tables, table_selecter);
}
}
else{
cout << "Unfortunately your answer isn't correct! :(" << "\n";
}
}
return 0;
}
As you can see the newquestion function for the mixed mode is quite different. Also the while loop includes other mixed mode specific code.
Now if I want to integrate the mixed multiplication tables mode into the existing main program I have 2 choices:
-I can clutter up the while loop with if-else statements to check each time the loop runs whether mode == 10 (single multiplication table mode) or mode == 100 (mixed multiplication tables mode). And also place a if-else statement in the newquestion() function to check if mode == 10 or mode == 100
-I can let the program check on startup whether the user chose single multiplication table or mixed multiplication tables mode and create 2 while loops and 2 newquestion() functions. That would look like this:
int newquestion_mixed(){
//newquestion function for mixed mode
}
int newquestion_single(){
//newquestion function for single mode
}
//initialization
if mode == 10
//create necessary variables for single mode
while(){
//single mode loop
}
else{
//create necessary variables for mixed mode
while(){
//mixed mode loop
}
}
Now why would I bother creating 2 separate loops and functions? Well isn't it inefficient if the program checks each time the loop runs (each time the user is asked a new question, for example: '5 * 3 =') which mode the user chose? I'm worried about the performance with this option. Now I hear you think: but why would you bother about performance for such a simple, little non-performance critical application with the extremely powerful processors today and the huge amounts of RAM? Well, as I said earlier this program is mainly about teaching myself a good coding style and learning how to program etc. So I want to teach myself the good habits from the beginning.
The 2 while loops and functions option is much more efficient will use less CPU, but more space and includes duplicating code. I don't know if this is a good style either.
So basically I'm asking the experts what's the best style/way to handle this kind of things. Also if you spot something bad in my code/bad style please tell me, I'm very open to feedback because I'm still a novice. ;)
First, a fundamental rule of programming is that of "don't prematurely optimize the code" - that is, don't fiddle around with little details, before you have the code working correctly, and write code that expresses what you want done as clearly as possible. This is good coding style. To obsess over the details of "which is faster" (in a loop that spends most of it's time waiting for the user to input some number) is not good coding style.
Once it's working correcetly, analyse (using for example a profiler tool) where the code is spending it's time (assuming performance is a major factor in the first place). Once you have located the major "hotspot", then try to make that better in some way - how you go about that depends very much on what that particular hot-spot code does.
As to which performs best will highly depend on details the code and the compiler (and which compiler optimizations are chosen). It is quite likely that having an if inside a while-loop will run slower, but modern compilers are quite clever, and I have certainly seen cases where the compiler hoists such a choice out of the loop, in cases where the conditions don't change. Having two while-loops is harder for the compiler to "make better", because it most likely won't see that you are doing the same thing in both loops [because the compiler works from the bottom of the parse-tree up, and it will optimize the inside of the while-loop first, then go out to the if-else side, and at that point it's "lost track" of what's going on inside each loop].
Which is clearer, to have one while loop with an if inside, or an if with two while-loops, that's another good question.
Of course, the object oriented solution is to have two classes - one for mixed, another for single - and just run one loop, that calls the relevant (virtual) member function of the object created based on an if-else statement before the loop.
Modern CPU branch predictors are so good that if during the loop the condition never changes, it will probably be as fast as having two while loops in each branch.
I have a method in my project which when placed into its own program takes mere seconds to run, when run inside the project where it belongs it takes 5 minutes. I have NO idea why. I have tried profiling, taking bits out, changing this and that. I'm stumped.
It populates a vector of integers to be used by another class, but this class is not currently being instantiated. I have checked as much as I can and it does seem as if there really is nothing else happening but the method magically taking longer in one project than it does in another.
The method is run at startup and takes about 5 minutes, or about 3 seconds if run on its own. What could be causing this? Strange project settings? Multithreading stuff that I'm unaware of? (as far as I know there is none in my project anyway unless it's done automatically).
There is a link to the project here. If anyone could solve this for me I would be so grateful, and as soon as I can will start a bounty for this.
The method is called PopulatePathVectors and runs in Level.cpp. Commenting out the call to the method (in the level constructor) means the program starts up in seconds. The only other class that uses the lists it generates is Agent, but currently none are being instantiated.
EDIT - As requested, here is the code. Although keep in mind that my question is not 'why is the code slow?' but 'why is it fast in one place and slow in my project?'
//parses the text path vector into the engine
void Level::PopulatePathVectors(string pathTable)
{
// Read the file line by line.
ifstream myFile(pathTable);
for (unsigned int i = 0; i < nodes.size(); i++)
{
pathLookupVectors.push_back(vector<vector<int>>());
for (unsigned int j = 0; j < nodes.size(); j++)
{
string line;
if (getline(myFile, line)) //enter if a line is read successfully
{
stringstream ss(line);
istream_iterator<int> begin(ss), end;
pathLookupVectors[i].push_back(vector<int>(begin, end));
}
}
}
}
EDIT - I understand that the code is not the best it could be, but that isn't the point here. It runs quickly on it's own - about 3 seconds and that's fine for me. The problem I'm tying to solve is why it takes so much longer inside the project.
EDIT - I commented out all of the game code apart from the main game loop. I placed the method into the initialize section of the code which is run once on start up. Apart from a few methods setting up a window it's now pretty much the same as the program with ONLY the method in, only it STILL takes about 5 minutes to run. Now I know it has nothing to do with dependencies on the pathLookupVectors. Also, I know it's not a memory thing where the computer starts writing to the hard drive because while the slow program is chugging away running the method, I can open another instance of VS and run the single method program at the same time which completes in seconds. I realise that the problem might be some basic settings, but I'm not experienced so apologies if this does disappointingly end up being the reason why. I still don't have a clue why it's taking so much longer.
It would be great if this didn't take so long in debug mode as it means waiting 5 minutes every time I make a change. There MUST be a reason why this is being so slow here. These are the other included headers in the cut down project:
#include <d3d10.h>
#include <d3dx10.h>
#include "direct3D.h"
#include "game.h"
#include "Mesh.h"
#include "Camera.h"
#include "Level.h"
#include <vector>
using namespace std;
EDIT - this is a much smaller self contained project with only a tiny bit of code where the problem still happens.
this is also a very small project with the same code where it runs very fast.
I ran this code in MSVC10 (same compiler you are using) and duplicated your results with the projects you provided. However I was unable to profile with this compiler due to using the express version.
I ran this code in the MSVC9 compiler, and it ran 5 times faster! I also profiled it, and got these results:
Initialize (97.43%)
std::vector::_Assign (29.82%)
std::vector::erase (12.86%)
std::vector::_Make_iter (3.71%)
std::_Vector_const_iterator (3.14%)
std::_Iterator_base (3.71%)
std::~_Ranit (3.64%)
std::getline (27.74%)
std::basic_string::append (12.16%)
std::basic_string::_Grow (3.66%)
std::basic_string::_Eos (3.43%)
std::basic_streambuf::snextc (5.61%)
std::operator<<(std::string) (13.04%)
std::basic_streambuf::sputc(5.84%)
std::vector::push_back (11.84%)
std::_Uninit_move::?? (3.32%)
std::basic_istream::operator>>(int) (7.77%)
std::num_get::get (4.6%)
std::num_get::do_get (4.55%)
The "fast" version got these results: (scaled to match other times):
Initialize (97.42%)
std::_Uninit_copy (31.72%)
std::_Construct (18.58%)
std::_Vector_const_iterator::operator++ (6.34%)
std::_Vector_const_iterator::operator!= (3.62%)
std::getline (25.37%)
std::getline (13.14%)
std::basic_ios::widen (12.23%)
std::_Construct (18.58%)
std::vector::vector (14.05%)
std::_Destroy (14.95%)
std::vector::~vector (11.33%)
std::vector::_Tidy (23.46%)
std::_Destroy (19.89%)
std::vector::~vector (12.23%)
[ntdll.dll] (3.62%)
After studying these results and considering Michael Price's comments many times, it dawned on me to make sure the input files were the same size. When this dawned on me, I realized the profile for the "fast" version, does not show std::operator<<(std::string) or std::vector::push_back at all, which seems suspicious. I checked the MethodTest project, and found that it did not have a WepTestLevelPathTable.txt, causing the getline to fail, and the entire function to do almost nothing at all, except allocate a bunch of empty vectors. When I copied the WepTestLevelPathTable.txt to the MethodTest project, it is exactly the same speed as the "slow" verison. Case solved. Use a smaller file for debug builds.
Here're a few methods I believe could slow down the start-up process:
Level::GenerateGridNodes():
void Level::GenerateGridNodes()
{
int gridHeight = gridSize;
int gridWidth = gridSize;
// ADD THIS STATEMENT:
nodes.reserve(gridHeight*gridWidth);
for (int h = 2; h <= gridHeight; h++)
{
for (int w = 2; w <= gridWidth; w++)
{
nodes.push_back(Node(D3DXVECTOR3((float)w, (float)h, 0)));
}
}
}//end GenerateGridNodes()
Level::CullInvalidNodes(): For std::vectors, use remove-erase idiom to make erasing elements faster. You also need to re-think of how this function should work because it seems to have lots of redudant erasing and adding of nodes. Would it make sense in the code that instead of erasing you could simply assign the value you push_back() right after deletion to the value you're erasing? So instead of v.erase(itr) followed by v.push_back(new_element), you could simply do *itr = new_element;? DISCLAIMER: I haven't looked at actually what the functions does. Honestly, I don't have the time for that. I'm just pointing you to a possiblity.
In Level::LinkNodes():
void Level::LinkNodes()
{
//generates a vector for every node
// ADD THIS BEFORE THE FOR LOOP
nodeAdjacencyVectors.reserve(nodes.size());
for (unsigned int i = 0; ....)
//... Rest of the code
}//end LinkNodes()
In short, you still have got room for a lot of improvement. I believe the main hog is the Level class functions. You should have another look through it and probably rethink how each function should be implemented. Especially those invoked within the constructor of Level class.
It contained a loop withing a loop, each inner loop reads each line of an over 30MB data file. Of course it's going to be slow. I would say it's slow by design.
I understand this is a classic programming problem and therefore I want to be clear I'm not looking for code as a solution, but would appreciate a push in the right direction. I'm learning C++ and as part of the learning process I'm attempting some programming problems. I'm attempting to write a program which deals with numbers up to factorial of 1billion. Obviously these are going to be enormous numbers and way too big to be dealing with using normal arithmetic operations. Any indication as to what direction I should go in trying to solve this type of problem would be appreciated.
I'd rather try to solve this without using additional libraries if possible
Thanks
PS - the problem is here http://www.codechef.com/problems/FCTRL
Here's the method I used to solve the problem, this was achieved by reading the comments below:
Solution -- The number 5 is a prime factor of any number ending in zero. Therefore, dividing the factorial number by 5, recursively, and adding the quotients, you get the number of trailing zeros in the factorial result
E.G. - Number of trailing zeros in 126! = 31
126/5 = 25 remainder 1
25/5 = 5 remainder 0
5/5 = 1 remainder 0
25 + 5 + 1 = 31
This works for any value, just keep dividing until the quotient is less
than 5
Skimmed this question, not sure if I really got it right but here's a deductive guess:
First question - how do you get a zero on the end of the number? By multiplying by 10.
How do you multiply by 10? either by multiplying by either a 10 or by 2 x 5...
So, for X! how many 10s and 2x5s do you have...?
(luckily 2 & 5 are prime numbers)
edit: Here's another hint - I don't think you need to do any multiplication. Let me know if you need another hint.
Hint: you may not need to calculate N! in order to find the number of zeros at the end of N!
To solve this question, as Chris Johnson said you have to look at number of 0's.
The factors of 10 will be 1,2,5,10 itself. So, you can go through each of the numbers of N! and write them in terms of 2^x * 5^y * 10^z. Discard other factors of the numbers.
Now the answer will be greaterof(x,y)+z.
One interesting thing I learn from this question is, its always better to store factorial of a number in terms of prime factors for easy comparisons.
To actually x^y, there is an easy method used in RSA algorithm, which don't remember. I will try to update the post if I find one.
This isn't a good answer to your question as you've modified it a bit from what I originally read. But I will leave it here anyway to demonstrate the impracticality of actually trying to do the calculations by main brute force.
One billion factorial is going to be out of reach of any bignum library. Such numbers will require more space to represent than almost anybody has in RAM. You are going to have to start paging the numbers in from storage as you work on them. There are ways to do this. The guy who recently calculated π out to 2700 billion places used such a library
Do not use the naive method. If you need to calculate the factorial, use a fast algorithm: http://www.luschny.de/math/factorial/FastFactorialFunctions.htm
I think that you should come up with a way to solve the problem in pseudo code before you begin to think about C++ or any other language for that matter. The nature of the question as some have pointed out is more of an algorithm problem than a C++ problem. Those who suggest searching for some obscure library are pointing you in the direction of a slippery slope, because learning to program is learning how to think, right? Find a good algorithm analysis text and it will serve you well. In our department we teach from the CLRS text.
You need a "big number" package - either one you use or one you write yourself.
I'd recommend doing some research into "large number algorithms". You'll want to implement the C++ equivalent of Java's BigDecimal.
Another way to look at it is using the gamma function. You don't need to multiply all those values to get the right answer.
To start you off, you should store the number in some sort of array like a std::vector (a digit for each position in the array) and you need to find a certain algorithm that will calculate a factorial (maybe in some sort of specialized class). ;)
//SIMPLE FUNCTION TO COMPUTE THE FACTORIAL OF A NUMBER
//THIS ONLY WORKS UPTO N = 65
//CAN YOU SUGGEST HOW WE CAN IMPROVE IT TO COMPUTE FACTORIAL OF 400 PLEASE?
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int x); //function to compute factorial described below
int main()
{
int N; //= 150; //you can also get this as user input using cin.
cout<<"Enter intenger\n";
cin>>N;
factorial(N);
return 0;
}//end of main
int factorial(int x) //function to compute the factorial
{
int i, n;
long long unsigned results = 1;
for (i = 1; i<=x; i++)
{
results = results * i;
}
cout<<"Factorial of "<<x<<" is "<<results<<endl;
return results;
}