Why is this now negative 😭😭😭 | Sololearn: Learn to code for FREE!

0

# Why is this now 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);

12/7/2021 3:40:49 PM

Hillgate Sambo

+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.

+3

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.

+2

Oh... thank you I'll try it 😁

+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/

+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

+1

Abhishek Pandey your factorial program does not work as advertised. It suffers integer overflow for numbers greater than 12.

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.

0

Use long long int

0

Здесь все смотрю не на русском языке общаются)))

0

Юлия Залезняк https://www.sololearn.com/discuss/516185/?ref=app