Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python3中的for循环和while循环对于素因式分解的不同结果_Python 3.x_For Loop_While Loop - Fatal编程技术网

Python 3.x Python3中的for循环和while循环对于素因式分解的不同结果

Python 3.x Python3中的for循环和while循环对于素因式分解的不同结果,python-3.x,for-loop,while-loop,Python 3.x,For Loop,While Loop,我写了一个函数,返回给定整数的素数因子。对于我测试的案例,它似乎工作正常。这是原始函数 def prime_factors_2(num: int) -> set: factors = [] while num % 2 == 0: factors.append(2) num //= 2 i = 3 while i <= int(sqrt(num)) + 1: if num % i == 0:

我写了一个函数,返回给定整数的素数因子。对于我测试的案例,它似乎工作正常。这是原始函数

def prime_factors_2(num: int) -> set:
    factors = []
    while num % 2 == 0:
        factors.append(2)
        num //= 2
    i = 3
    while i <= int(sqrt(num)) + 1:
        if num % i == 0:
            factors.append(i)
            num //= i
        else:
            i += 2
    if num != 1:
        factors.append(num)
    return set(factors)
    # num = 867844
    # Output = {601, 2, 19}
def prime_factors_1(num: int) -> set:
    factors = []
    while num % 2 == 0:
        factors.append(2)
        num //= 2
    for i in range(3, int(sqrt(num)) + 1, 2):
        if num % i == 0:
            factors.append(i)
            num //= i
            print(num)
    if num != 1:
        factors.append(num)
    return set(factors)
    # num = 867844
    # Output = {2, 19, 11419}
出于某种原因,它不再将11419分为601和19。这两个循环不是等价的吗?还是我在将while循环转换为for循环时犯了一些错误?我知道在这种情况下,两个循环之间没有实际的区别,但我想知道这一点纯粹是出于好奇。

问题是,在“while循环”中,只有当“if”条件不满足时,才将“I”的值增加2,但在“for循环”的情况下,每次迭代中,I都会增加2

因此,如果您要执行以下操作:

while i <= int(sqrt(num)) + 1:
    if num % i == 0:
        factors.append(i)
        num //= i
    i += 2
while i问题在于,在“while循环”中,仅当“if”条件不满足时,才将“i”的值增加2,但在“for循环”的情况下,每次迭代中,i将增加2

因此,如果您要执行以下操作:

while i <= int(sqrt(num)) + 1:
    if num % i == 0:
        factors.append(i)
        num //= i
    i += 2

而i这两个函数之间有一点不同

如果仔细观察while循环中的
prime\u factors\u 2
,当满足
If
条件时,计数器不会增加

另一方面,在for循环中的
prime\u factors\u 1
中,无论
if
条件如何,计数器在每次迭代中都会递增


无法从for循环中控制计数器,因此while循环实现是唯一正确的方法。

这两个函数之间有一点不同

如果仔细观察while循环中的
prime\u factors\u 2
,当满足
If
条件时,计数器不会增加

另一方面,在for循环中的
prime\u factors\u 1
中,无论
if
条件如何,计数器在每次迭代中都会递增

无法从for循环中控制计数器,因此while循环实现是唯一正确的方法