Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.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 输入一个数字并找出其系数-回答错误_Python - Fatal编程技术网

Python 输入一个数字并找出其系数-回答错误

Python 输入一个数字并找出其系数-回答错误,python,Python,我编写了一个简单的代码,用于输入一个数字,找到它的因子并打印它们: import math n=int(input("Enter your number : ")) i=int(math.sqrt(n)+1) while i !=0: if n%i==0: print(i) i=i-1 但由于某些原因,它并没有给我正确的答案 输出: Enter your number : 35 5 1 好吧,所以我很愚蠢,写了我自己问题的答案 import

我编写了一个简单的代码,用于输入一个数字,找到它的因子并打印它们:

import math
n=int(input("Enter your number : "))
i=int(math.sqrt(n)+1)
while i !=0:
    if n%i==0:
        print(i)
    i=i-1
但由于某些原因,它并没有给我正确的答案

输出:

Enter your number : 35
5
1

好吧,所以我很愚蠢,写了我自己问题的答案

import math
n= 35#int(input("Enter your number : "))
i=int(math.sqrt(n)+1)
while i !=0:
    if n%i==0:
        print(i)
        print(n/i)
    i=i-1

这实际上是最有效的方法

这将快速获得一个因子列表,首先获得一个素数因子列表和每个素数的幂,然后将它们在所有组合中相乘。请注意,候选数不一定都是素数,但它们确实包括所有素数

import itertools

def gen_candidates():
    yield 2
    yield 3
    c = 0
    while True:
        c += 6
        yield c - 1
        yield c + 1

def gen_prime_factors_with_powers(x):
    for c in gen_candidates():
        if c * c > x:
            yield (x, 1)
            return
        power = 0
        while x % c == 0:
            power += 1
            x //= c
        if power:
            yield (c, power)
            if x == 1:
                break

def product(lst):
    prod = 1
    for item in lst:
        prod *= item
    return prod
    
def get_factors(x):

    factors = [[(pf ** i) for i in range(1 + power)]
               for pf, power in gen_prime_factors_with_powers(x)]
    return sorted([product(lst) for lst in itertools.product(*factors)])

print(get_factors(12345678909876543210))

显然,如果主要因素本身较大,则可能仍需要一些时间,但它只会搜索以下较大的因素:

  • 第二大主要因素
  • 最大素因子的平方根

它最多搜索不到
x
,只有在质数的最坏情况下,它甚至搜索到x的平方根。

您假设
n
的任何因子都不能超过其平方根。但是它确实存在。你可以通过把n除以它的因子,小于平方根,很容易地找到它们@jonrsharpe事实上你是对的,你能重写代码吗?你可能想单独处理这个问题,不过,它会打印两次系数。