-3

Large integer number is showing incorrect output even after using long in bellow code, but still it is showing incorrect result. How I can improve?

 #include<stdio.h>
    #include<conio.h>
    void main()
    {

     long a, b, result;
     a=1234;
     b=19887815769532909;
     result= (0.5)*(a+b)*(a+b+1)*b;
     printf("%d", result);
     getch();

    }

but output is showing something like : -2147483648

I think I am doing something wrong with variable with large number. I have also tried int long but failed.

Please help.

prohor
  • 21
  • 5
  • 1
    `19887815769532909` requires a 64-bit integer. – Weather Vane Apr 21 '17 at 19:16
  • 1
    . . . but `19887815769532909` (effectively) cubed requires a bigint library. – Weather Vane Apr 21 '17 at 19:27
  • `long result` cannot represent every possible integer. It has a limited range exceed by `(0.5)*(a+b)*(a+b+1)*b`. Try `double result = (0.5)*(a+b)*(a+b+1)*b; printf("%e\n", result);` – chux - Reinstate Monica Apr 21 '17 at 19:34
  • . . . although the purpose of the `double 0.5` is unclear in this context. Did you want a `double` result? Otherwise, better to halve a big integer. – Weather Vane Apr 21 '17 at 19:35
  • If you're printing a `long`, you need to use `%ld` and not just `%d`. However, you also have problems because your value is too big to fit into a `long` (or, indeed, a `long long` on most machines). But you're exacerbating the problem by using an incorrect conversion specifier in the format. Don't forget to print a newline too! – Jonathan Leffler Apr 21 '17 at 19:49

1 Answers1

0

As mentioned in the comments you need to use long or long long in your calculations. Moreover, the statement result= (0.5)*(a+b)*(a+b+1)*b; is causing integer overflow which is why a negative value is being printed to the console(despite using %lld as a format specifier. You can look at the ranges of the integer variants here. If possible you should also check for integer overflow in your calculations, read this.

But if you want to perform operations on integers bigger than the range provided by standard C primitives, you might want to implement it on your own using character or integer arrays(converting high school methods into code). There are lots of tutorials about it.

I hope this helps.

Community
  • 1
  • 1
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40