反正阶乘函数反吗? [英] Anyway to inverse factorial function?

查看:121
本文介绍了反正阶乘函数反吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以问题来了,我是python的新手。

So the question comes like this, I'm new to python:

def factorial_cap(num):对于正整数 n ,n的阶乘(表示为 n!),是所有从1到n(含)的正整数的乘积
。实现返回最小的

正n这样n的函数!大于或等于参数num。
o假设:num始终是一个正整数。

def factorial_cap(num): For positive integer n, the factorial of n (denoted as n!), is the product of all positive integers from 1 to n inclusive. Implement the function that returns the smallest
positive n such that n! is greater than or equal to argument num. o Assumption: num will always be a positive integer.

# Examples 
# factorial_cap(20) output is 4  since 3!<20 but 4!>20
# factorial_cap(24) output is 4 since 4!=24
# factorial_cap(1) output is 1 since 1!=1

# And here is what I got

def factorial_cap(num):
    n = 1
    for i in range (1,num+1):
        n = n*i    

我很确定这是阶乘定义的正确函数。但是我只是想不通,而不是获得总价值,我如何才能像上面发布的示例那样获得正确的输出?

I'm pretty sure this is the right function for factorial def. But I just couldn't figure out, instead of getting the 'total value', how can I just get the right output as I posted example above?

Btw,应该我在def的末尾使用 return,还是在这种情况下没关系?

Btw, should I use 'return' at the end of def, or it does not matter in this case?

推荐答案

需要对当前总数大于或等于请求数量的条件进行测试。因此,您可以使用while循环的条件来执行该检查,并增加一个计数器 i 来跟踪当前迭代。然后只需返回当前值 i 即可得出值> =所需数字:

There needs to be a test for when the current total is greater than or equal to the requested number. So you can use the condition of a while loop to perform that check, and increment a counter, i, that keeps track of the current iteration. Then it's a matter of returning the current value of i that produced the value >= the required number:

def factorial_cap(num):
    n = 1
    i = 1
    while n < num:
        i += 1   
        n *= i
    return i

>>> factorial_cap(20)
4
>>> factorial_cap(24)
4
>>> factorial_cap(25)
5
>>> factorial_cap(1)
1
>>> factorial_cap(3628800)
10

这篇关于反正阶乘函数反吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆