29426

Factorial does not work for all values

Question:

Hi everyone I edited my post because I have another problem with my code.I had a problem with the factorial function yesterday but I managed to solve it thanks to your answers , it was a ridiculous mistake. The problem now is that for some values that are higher than 15, the final results(not the factorials of individual numbers) are always 0 or -1 for the lesser values it works fine.Can someone tell me whats wrong with this code :

#include <iostream> #include<time.h> using namespace std; int factorial(int a){ if(a==1) return 1; else if(a==0) return 1; else return factorial(a-1)*a; } int main(){ std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); int n,k; int x,y,z,w,v; cout<<"give n : "; cin>>n; cout<<"give k : "; cin>>k; clock_t t; t = clock(); if(n>=k&&k>1){ x=factorial(n-1); y=factorial(k-1); z=factorial(n-1-k); w=factorial(n-k); v=factorial(k); cout<<"Result is "<<(x/(v*z))+(x/(y*w))<<endl; } else if (n==0||n==k) cout<<"Result is 1"<<endl; else cout<<"Result is 0"<<endl; t = clock() - t; cout<<"It took "<<t<<" clicks ("<<((float)t)/CLOCKS_PER_SEC<<" seconds )"<<endl; return 0; }

Answer1:

Integer overflow.

If int is 32 bits on your system, the largest value it can represent is 2147483647. 13 factorial is 6227020800.

If you use a 64-bit integer type such a long long, you can go up to 20 factorial.

Floating-point will give you more range, but with a loss of precision.

If you really need to compute large factorials, you'll need to use some multi-precision library like <a href="http://gmplib.org/" rel="nofollow">GMP</a>, or use a language that has built-in arbitrary-precision integer arithmetic (C doesn't).

Answer2:

The following might call factorial with a zero or negative argument:

z=factorial(n-1-k); w=factorial(n-k);

You need to make sure that your factorial function can handle such arguments without crashing (I suspect it doesn't).

Recommend

  • python object not iterable error in function
  • C++ String tokenisation from 3D .obj files
  • Is there a difference between initializing a variable in the default constructor or inline? [duplica
  • C++ Coin flip program error
  • string.IsNullOrEmpty() Doesn't Seem to Work on a String within a Class within a Class
  • Call a php script whenever an e-mail is received?
  • runtime-check whether an instance (Base*) override a parent function (Base::f())
  • Building Qt project for C++11 standard
  • C++ friend class std::vector
  • WPF Template Binding in ToggleButton UserControl
  • Error in installing package: fatal error: stdlib.h: no such file or directory
  • Thread 1: EXC_BAD_ACCESS (code =1 address = 0x0)
  • How to determine if there are bytes available to be read from boost:asio:serial_port
  • Atlas images wrong size on iPad iOS 9
  • $wpdb not working in file of WordPress plugin
  • Meteor: Do Something On Email Verification Confirmation
  • Meteor helpers not available in Angular template
  • Sony Xperia Z Tablet not found by adb
  • How to recover from a Spring Social ExpiredAuthorizationException
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Where to put my custom functions in Wordpress?
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • How can I estimate amount of memory left with calling System.gc()?
  • RestKit - RKRequestDelegate does not exist
  • Buffer size for converting unsigned long to string
  • WPF Applying a trigger on binding failure
  • Hits per day in Google Big Query
  • embed rChart in Markdown
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • How can I remove ASP.NET Designer.cs files?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Checking variable from a different class in C#
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal