简体   繁体   English

在此python主要因子程序中寻找反例

[英]Looking for counterexample in this python prime factors program

I cobbled together this script to spit out the prime factorization of an integer n . 我拼凑了这个脚本,以吐出整数n的素数分解。 At the very end of the script, I multiply the current list of prime factors, including multiplicity, and check if its equal to n ; 在脚本的最后,我将当前素数列表(包括多重性)相乘,并检查其是否等于n if not, I divide out that product and append the quotient if it's prime. 如果不是,我将那个产品除以商,如果它是质数则附加商。

I've tested a ton of numbers, and it's worked each time, but mathematically I'm not sure why. 我已经测试了大量的数字,并且每次都有效,但是从数学上我不确定为什么。 Shouldn't I have to loop that bit about checking for leftover primes in the range (sqrt(n), n) ? 我是否应该就检查range (sqrt(n), n)剩余质数而循环一下? Couldn't there be an integer with two primes in that range? 不能有一个在这个范围内有两个素数的整数吗? If there is, I haven't been able to find an example yet. 如果有,我还没有找到一个例子。 I'm new to python, so another explanation is that I don't understand my own code, and its looping for me somehow. 我是python的新手,所以另一个解释是,我不理解自己的代码,而且它以某种方式对我来说循环。

from math import sqrt
n = int(input("Let's factor a number:"))

def isPrime(x):
    for i in range(2,int(sqrt(x)+1)):
        if x%i==0:
            return False
    return True

m = int(sqrt(n)+1)
i = 1
factors = []
while(1 < m):
    if (n % (m**i) == 0 and isPrime(m) == True):
        factors.append(m)
    else:
        m -= 1
        i = 1
        continue
    i += 1

prod = 1
for i in factors:
    prod *= i

if prod == n:
    print(factors)
elif isPrime(n/prod) == True:
    factors.append(int(n/prod))
    print(factors)

No, you don't need such a loop. 不,您不需要这样的循环。 n can have only one prime factor > sqrt(n) . n只能有一个素数> sqrt(n) Assume the opposite: there are at least two. 假设相反:至少有两个。 i, j > sqrt(n). i,j> sqrt(n)。 In this case, i*j must be > sqrt(n)*sqrt(n), and there's your contradiction. 在这种情况下,i * j必须为> sqrt(n)* sqrt(n),这是您的矛盾之处。

Once you've found all factors less than sqrt(n) , any remaining amount is prime, and would be the only factor larger than sqrt(n) . 一旦发现所有小于sqrt(n)因数,任何剩余量都是素数,并且是唯一大于sqrt(n)因数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM