Reputation: 15875
I am trying something on my Mac OS X XCode 7.2.1 -
#define uint64 unsigned long long
int N = 100000;
uint64 value = (pow(N, 4) + 2 * pow(N, 3) + 3 * pow(N, 2) + 2 * N) / 4;
cout << "value: " << value << endl; // this is equivalent to ULLONG_MAX (18446744073709551615)
cout << "ULLONG_MAX: " << ULLONG_MAX << endl;
So the output is supposed to be -
value: 18446744073709551615
ULLONG_MAX: 18446744073709551615
But the output is -
value: 0
ULLONG_MAX: 18446744073709551615
Also below changes didn't make any difference.
uint64 N = 100000ull;
uint64 value = (pow(N, 4ull) + 2ull * pow(N, 3ull) + 3ull * pow(N, 2ull) + 2ull * N) / 4ull;
Running gcc --version
command on my terminal yields -
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.0.0
Thread model: posix
I tried above code in Hackerrank g++ 4.9.2 compiler and the output was correct.
What's happening under the hood? Is it Clang or my OS(Mac OS X 10.11)?
Upvotes: 1
Views: 1041
Reputation: 4888
This is caused by overflow. Your equation returns: 25000500007500050000 which is to large for an unsigned long long.
It would seem like clang handles this slightly differently from g++. I made a small test to see what the result became after the cast.
See: Clang giving random values while g++ returns std::numeric_limits<std::uint64_t>::max()
.
Should you need this number (in a datatype) I would personally advise finding a library that supports arbitrary length numbers (gmp or comparable).
Upvotes: 4