Larry
Larry

Reputation: 1765

Wrong calculation result on uint64_t

Context

Debian 64bits.

I have this code

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

int main(int argc, char ** argv){

    uint64_t b = 5000000000;/* 5 000 000 000 */
    uint64_t a = (b*b)/2;

    printf("a = %llu\n",a);

return 0;
}

Problem

Javascript, my hand calculator and the virtual calculator in my operating system give me a result of 1.25×10^19 whereas my c program above gives a = 3276627963145224192

What am I doing wrong ?

Upvotes: 1

Views: 656

Answers (3)

Sathish
Sathish

Reputation: 3870

uint64_t can't hold the result of b*b.

The result of b*b is 25000000000000000000. That is 25x10^18.

But uint64_t can hold maximum value upto 6553255926290448384. Hence overflow occurs in b*b operation.

Due to this overflow you are not getting the actual result!

Upvotes: 1

0xF1
0xF1

Reputation: 6116

Your intermediate operation of b*b has value which is greater than what a 64-bit register can hold, hence it overflows.

Since, b (= 5 000 000 000) > 2^32, hence, b*b > 2^64

And, since 5000000000 * 5000000000 / 2 can never fit into 64-bit variable, you cannot calculate this value in C without using special methods like representing number using arrays.

Also, as @Joachim Pileborg suggested, you should assign unsigned long long value to b as

uint64_t b = 5000000000ull;

Upvotes: 1

ravin.wang
ravin.wang

Reputation: 1252

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

int main(int argc, char ** argv){

    uint64_t b = 5000000000LL;/* 5 000 000 000 */
    uint64_t a = (((uint64_t)b)*b)/2LL;

    printf("a = %llu\n",a);

return 0;
}

Upvotes: 0

Related Questions