user5179581
user5179581

Reputation:

Find highest factorial less than n

I'm trying to find the highest factorial less than a number n.

Here is my code so far:

import math 

def highestNum(n):
    list = [] 
    k = 0 
    f = math.factorial(k)  

    while f < n:
        list.append(f)
        k += 1 
    print list 

highestNum(1000)

The code has an error causing it to not print anything. Any tips on how to improve this code so it works?

For example, highestNum(25) should print [1, 2, 6, 24].

Upvotes: 0

Views: 371

Answers (2)

vaultah
vaultah

Reputation: 46563

In your code f = math.factorial(k) is evaluated once (before the while loop). The value of f is constant (0! = 1), this means that f < n is True for n > 1. That is the reason why the loop runs forever.

Either re-evaluate f within the loop or switch to simple multiplication, which is preferred, since math.factorial(k) will eventually become slow and you have a loop counter (k) anyway:

def highestNum(n):
    lst = [] 
    k = 1 # start with 1
    f = 1 # math.factorial(1) is 1
    while f < n:
        lst.append(f)
        k += 1
        f *= k

Upvotes: 1

Eduardo Mauro
Eduardo Mauro

Reputation: 1515

Your code is wrong. You calculate the factorial of k, which is initially zero. So f remains equal 1 all the time and the condition f < n is always true and it enter in an endless loop. Nothing will be printed. You should rewrite your code.

Upvotes: 0

Related Questions