TerasVallo
TerasVallo

Reputation: 71

My python program keeps returning the wrong value doubled

We are supposed to create a program that for positive integer n, the factorial of n

  1. factorial_cap(1) → 1 ......#1!=1

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

Answers (1)

user2464424
user2464424

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

Related Questions