什么是发现了一些在Python中的所有因素中最有效的方法是什么? [英] What is the most efficient way of finding all the factors of a number in Python?

查看:118
本文介绍了什么是发现了一些在Python中的所有因素中最有效的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我解释一下发现一些的所有因素在Python的有效方法(2.7)?

我可以创建算法来做好这项工作,但我认为这是糟糕codeD,和时间太长了大量的执行结果。

解决方案

高清因素(N):     返回集(减少(表.__ add__,                 ([I,N //我对于我的range(1,INT(N ** 0.5)+ 1)如果n%我== 0)))

这将返回一个数字的所有因素,速度非常快, N

为什么平方根为上限?

的sqrt(x)的* SQRT(X)= X 。因此,如果这两个因素是相同的,它们都是平方根。如果你做一个大的因素,你必须让其他的因素较小。这意味着,这两个中的一个将始终小于或等于的sqrt(x),所以你只需要寻找到这一点,找到两个匹配之一因素。然后,您可以使用 X / FAC1 获得 FAC2

减少(表.__ add__,...)走的是小名单[FAC1,FAC2] 并加入他们一起在一个长长的清单。

[I,N / I]为我的range(1,INT(SQRT(N))+ 1)如果n%我== 0 返回对因素,如果当你把剩下的 N 以较小的一个是零(它并不需要检查较大的一个也一样,它只是获取除以ñ的较小的一个。)

设置(...)在外面摆脱重复的。我想,这只是发生了完美的正方形。对于 N = 4 ,这将返回 2 的两倍,所以设置摆脱其中的一个。

编辑: 开方实际上是快于 ** 0.5 ,但我会离开它,因为它是很好的作为一个独立的片段。

Can someone explain to me an efficient way of finding all the factors of a number in Python (2.7)?

I can create algorithms to do this job, but i think it is poorly coded, and takes too long to execute a result for a large numbers.

解决方案

def factors(n):    
    return set(reduce(list.__add__, 
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

This will return all of the factors, very quickly, of a number n.

Why square root as the upper limit?

sqrt(x) * sqrt(x) = x. So if the two factors are the same, they're both the square root. If you make one factor bigger, you have to make the other factor smaller. This means that one of the two will always be less than or equal to sqrt(x), so you only have to search up to that point to find one of the two matching factors. You can then use x / fac1 to get fac2

the reduce(list.__add__, ...) is taking the little lists of [fac1, fac2] and joining them together in one long list.

The [i, n/i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0 returns a pair of factors if the remainder when you divide n by the smaller one is zero (it doesn't need to check the larger one too, it just gets that by dividing n by the smaller one.)

The set(...) on the outside is getting rid of duplicates. I think this only happens for perfect squares. For n = 4, this will return 2 twice, so set gets rid of one of them.

Edit: sqrt is actually faster than **0.5, but I'll leave it out as it's nice as a self-contained snippet.

这篇关于什么是发现了一些在Python中的所有因素中最有效的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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