Very large integer does not work

Asked

Viewed 180 times

4

My code is like this:

#include <stdio.h>

int main()
{
    unsigned long int L, N;
    scanf("%lu%lu", &L, &N);

    printf("%lu\n", (L-(N-1))*(L-(N-1)) + (N-1));

    return 0;
}

When the test case has low numbers, the program works. However, when the numbers are beyond the capacity of the unsigned long int, with entries like 1,000,000 and 9 (the correct answer would be 999984000072) the program gives the wrong answer.

How can I operate with larger integers?

2 answers

8


If you have a C99 implementation, you can try unsigned long long. This guy has to exist, but it may not be bigger than unsigned long --- and therefore may not solve your problem.

Check with, for example sizeof (unsigned long) == sizeof (unsigned long long)

If you can use this guy, remember to use "%llu" both in printfs and scanfs.

In that case, either use a library for large numbers or do your version of number multiplication as you learned in primary school (a very interesting project).

  • 1

    or ... cheat: sprintf(cmd, "echo 'n=%lu; l=%lu; print (l-(n-1))*(l-(n-1))+(n-1)' | python", n, l); system(cmd);

  • Oh! Just one more thing. The conversation strings for unsigned long long use %llu in both printf and scanf.

6

Browser other questions tagged

You are not signed in. Login or sign up in order to post.