Back to General discussions forum
I have done this problem for a day now, and its really bothering me that i cant seem to solve it. I tried to figure out if the code was spitting out wrong numbers so i tried to "debug" it, this was the code i wrote.
int main() { int userChoice, number; unsigned long int result = 0; int seed = 113, limit = 10000007; cin >> userChoice;
int arr[userChoice];
for(int i = 0; i < userChoice; i++)
{
cin >> number;
arr[i] = number;
}
cout << endl << endl;
for(int i = 0; i < userChoice; i++)
{
cout << endl;
cout << "result = (" << result << " + " << arr[i] << ") * 113 = ";
result = (result + arr[i]) * seed;
cout << result << " ";
if(result > limit)
{
cout << "True";
result = result % 10000007;
}
else
cout << "False";
cout << endl;
}
cout << endl << result;
return 0;
}
i did the math myself, on paper, and got the same answers in the practice question the page gives you. no matter what numbers it gives me to solve, it never gets it right, and im not sure why at this point. please help.
I can see 3 things wrong with your code.
If result==limit you still need to take the modulo.
When printing the result, you need cout << result << endl;
Also, with the compiler you are using, check that sizeof(unsigned long int) is bigger than sizeof(unsigned).
If you are still stuck, please show the test data it fails with and the answer your code gives.
i now check if result == limit, but im still not fully understanding the sizeof(unsigned long int) and sizeof(unsigned) part.
In some compilers an unsigned long is the same size as an unsigned.
Use this to check, cout << sizeof(unsigned long int) << " " << sizeof(unsigned) << endl;
unsigned long int is indeed the same size as unsigned in my compiler
It is likely that your calculation will be overflowing a 32 bit variable. Try using a long long.
using a long long fixed it thank you!
is there anything else i can learn out of this? i knew how to do the code expect for the small issue of having result being greater than or equal to the limit, but the long long thing really got me for about a week.
With some compilers an int and a long are the same size. On other compilers, a long and a long long are the same size. You just need to be aware of that and use sizeof to check.
I generally only use int (normally 32 bit) or long long (normally 64 bit).