Why is the factorial of a number >= 32 negative? | Sololearn: Learn to code for FREE!
0

Why is the factorial of a number >= 32 negative?

#include <iostream> using namespace std; int factorial(int n) { if (n==1) { return 1; } else { return n * factorial(n-1); } } int main() { cout << factorial(32);

7th Dec 2021, 3:40 PM
Hillgate Sambo
Hillgate Sambo - avatar
10 ответов
+ 4
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ that was good analysis in determining the problem was integer overflow. But I take opposition regarding getting different garbage values on subsequent runs. Integer overflow has a predictable and consistent result. It simply truncates the lost high bits. Effectively, it is the modulo of maximum unsigned integer+1. Sometimes the result looks negative only because the high bit happened to become 1 on a signed type.
7th Dec 2021, 8:01 PM
Brian
Brian - avatar
+ 2
Hillgate Sambo Because factorial of 32 would be beyond the size of int so you get garbage value in negative. Try to run again and again, you will get different garbage value.
7th Dec 2021, 3:44 PM
A͢J
A͢J - avatar
+ 2
Oh... thank you I'll try it 😁
7th Dec 2021, 3:52 PM
Hillgate Sambo
Hillgate Sambo - avatar
+ 2
Hillgate Sambo Yes even if we use unsigned long long int n then still the problem is same. You can see different data types and their size here: https://www.geeksforgeeks.org/c-data-types/
7th Dec 2021, 4:18 PM
A͢J
A͢J - avatar
+ 1
Use long long int
8th Dec 2021, 5:15 AM
Vishal Pandey
+ 1
Just run this program and find the factorial of Any integer yes any integer negative too. It is not possible to calculate factorial of negative numbers but it will it as positive input. https://www.sololearn.com/post/1415150/?ref=app
8th Dec 2021, 9:40 AM
Abhishek Pandey
Abhishek Pandey - avatar
+ 1
Abhishek Pandey your factorial program does not work as advertised. It suffers integer overflow for numbers greater than 12.
8th Dec 2021, 4:45 PM
Brian
Brian - avatar
0
But I'm still wondering... Is there any way we can make the program to read it ? Since calculators can calculate it faster ? I tried using ( long long int n )on function's parameter but still did not work.
7th Dec 2021, 4:02 PM
Hillgate Sambo
Hillgate Sambo - avatar
0
Здесь все смотрю не на русском языке общаются)))
9th Dec 2021, 5:56 AM
Юлия Залезняк
Юлия Залезняк - avatar