Hello, I'm trying to calculate big numbers but it's not working. I turned every variable into long and switched my project to x64. Here is my code. Thanks!
1 2 3 4 5 6 7 8 9
inlineunsignedlong calculatePossibleCombinations(unsignedlong slots, unsignedlong elements) {
unsignedlong possible_combinations = 1;
for (int i = 0; i < slots; i++)
possible_combinations *= elements;
return possible_combinations;
}
Your title says you are trying to do a long multiplication. You are, however, calculating 30 ^ 7. Is that what you are meaning to do? That answer would be 21,870,000,000.
=If you are trying to calculate 30 * 7, you need to addelements to possible_combinations every time through the loop.
Of course, if you actually are trying to calculate 30 ^ 7 and your system uses a 32-bit unsigned long, the maximum value that a 32-bit unsigned long can contain is 4,294,967,295
What does "not working mean"? Be specific. Is it giving some random junk number? Is your logic simply wrong? What is your expected output?
You're trying to find the number of ways to put N elements in M boxes, right? The answer is not as simple as M^N. I believe you want to use the formula in this link: https://math.stackexchange.com/a/192671
Your formula is is not doing this.
On line 5 you are comparing an int to an unsigned long, but this only produces a warning (and I don't think is the actual problem).
If it isn't the logic of the function that's wrong, I think the real error happens in how you're calling it.
Might be that your unsigned long is only 32-bit, but unsigned long long is correctly 64-bit. If your unsigned long long isn't big enough to hold your number, you're going to have to use big ints, as JLBorges suggests.
Yep, it would appear your unsigned long is only 32-bit (4294967295 = 2^{32} - 1). Change your initial program to use unsigned long long instead of unsigned long.
I replaced unsigned long with unsigned long long and it worked. But if slot is 14 and elements 27, the same thing happens again....
14^{27} > 2^{102}
You're working with numbers larger than 64-bit. I'm afraid you'll have to use a Big Integer library such as boost::multiprecision::cpp_int. See JLBorges's post.