I have the following code to calculate n!
import numpy as np
print "n! (for n<31)"
print
n = input("Enter n: ")
lst = []
for i in range(1,n+1):
lst.append(i)
print lst #Just to see if the program is working
print "n!: ", np.prod(lst)
However, for some numbers, the program returns a negative value.
Eg. The following is from the console when I ran it for n = 20:
n! (for n<31)
Enter n: 20
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
n!: -2102132736
It also happens for n = 32 However, the program does work for other numbers, eg. 3! returns 6, as it should.
Can someone please explain.
As I wrote in my comment, it's a 32bit problem. If you have a 64bit system, you can still calculate up to 20!
Here is a solution without numpy, with the python builtin types, which handle such problems pretty safely:
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
n = input("n! (for n<31)\n\nEnter n: ")
print("n!: %d" % factorial(n))
And here is a recursive function to bend your mind ;-)
def factorial_r(n):
if n < 2:
return 1
return n * factorial_r(n-1)
n = input("n! (for n<31)\n\nEnter n: ")
print("n!: %d" % factorial_r(n))