Reputation: 71
We are supposed to create a program that for positive integer n, the factorial of n
This is my code.
def factorial(num):
F = 0
x = 1
factor = 1
while (F <= num):
for i in range(1,x + 1):
factor = (factor * i)
if (F>=num):
return x
else:
x = x+1
print("The answer is", x)
F = factor
factorial_cap(24) I'm just using print statement to see what the output is, it keeps giving me The answer is 2 The answer is 4 The answer is 8, while the right answer is supposed to be 4, I can't stop it from looping and just return the value 4
Upvotes: 2
Views: 123
Reputation: 1616
The reason it keep printing the "the answer is" string is that the print
statement is placed directly inside the while loop, so it will trigger for every new attempt.
Try this approach (Python 2.7.8):
def factorial_cap(num):
print "Input number:", num
F = 1
x = 1
while (F < num):
x += 1
F *= x
print "The answer is:", x
return x
for t in xrange(0,30):
factorial_cap(t)
print
Or this (less efficient):
def factorial(num):
res = 1
for i in xrange(1,num+1):
res *= i
return res
def factorial_cap(num):
print "Input number:", num
F = 0
x = 0
while (F < num):
x = x+1
F = factorial(x)
print "The answer is:", x
return x
for t in xrange(0,30):
factorial_cap(t)
print
Upvotes: 2