如何检查给定数字在Python 3中是否为阶乘(保留)

问题描述 投票:-6回答:4

例如,24是阶乘,因为:

 4 * 3 * 2 * 1 = 24

代码应以24作为输入,而输出(请参见下文)应为是否为阶乘。

    return "is a factorial."
else:
    return "is not a factorial."
print("The number " + str(24) + " " + str(isFactorial(24)))
python python-3.x factorial
4个回答
0
投票

最简单的是将其倒退。生成阶乘,直到找到或不找到为止。这样,您就可以确保始终比较整数:

def is_factorial(n):
    i = f = 1
    while f < n:
        i += 1
        f *= i
    return f == n

0
投票

最简单的方法是将现成的大量阶乘数列表按这样的数组排序

 List: 1, 2, 6, 24, 120, ...

然后在此列表中搜索以查看您的电话号码是否有效由于列表已排序,因此我建议使用二进制搜索。

阶乘数Link的列表


0
投票

我为您提出2种解决方案:

def check_fact(n):
    i = fact = 1
    while fact<n:
        i += 1
        fact *= i
    return fact==n

def check_fact_opt(n):
    i = 1
    while n>1:
        if n % i == 0:
            n /= i
        else:
            break
        i+=1
    return n<=1

这两个解决方案都能产生相同的结果,并且都可以解决您的问题,但是后者要少得多的迭代次数:

        N          is_fact     n_it  is_fact_opt  n_it_opt
2               |   True    |   1   |   True    |   1   
6               |   True    |   2   |   True    |   2   
24              |   True    |   3   |   True    |   3   
50              |   False   |   4   |   False   |   2   
100             |   False   |   4   |   False   |   2   
120             |   True    |   4   |   True    |   4   
200             |   False   |   5   |   False   |   2   
500             |   False   |   5   |   False   |   2   
1000            |   False   |   6   |   False   |   2   
5040            |   True    |   6   |   True    |   6   
100000          |   False   |   8   |   False   |   2   
3628800         |   True    |   9   |   True    |   9   
3628801         |   False   |   10  |   False   |   1   
100000000000    |   False   |   14  |   False   |   2   

-3
投票

(急忙写的)

def isfac(n):
    i = 2
    while n > 1:
        n = n / i
        i = i + 1
    return n == 1
© www.soinside.com 2019 - 2024. All rights reserved.