Check sum in c

Back to General discussions forum

VitalxFA     2018-08-14 01:06:01

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.

Quandray     2018-08-14 06:44:55
User avatar

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.

VitalxFA     2018-08-17 20:20:49

i now check if result == limit, but im still not fully understanding the sizeof(unsigned long int) and sizeof(unsigned) part.

Quandray     2018-08-18 12:49:04
User avatar

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;

VitalxFA     2018-08-19 18:14:31

unsigned long int is indeed the same size as unsigned in my compiler

Quandray     2018-08-19 19:08:41
User avatar

It is likely that your calculation will be overflowing a 32 bit variable. Try using a long long.

VitalxFA     2018-08-19 20:05:50

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.

Quandray     2018-08-19 20:14:56
User avatar

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).

Please login and solve 5 problems to be able to post at forum