【问题标题】:How do I stop this fast factorization program from printing beyond the 3rd output?如何阻止这个快速分解程序在第三个输出之后打印?
【发布时间】:2019-12-07 14:18:09
【问题描述】:

我在打印过程中遇到了这个 python37 代码的问题,我不希望它打印输出中的素数以进行因式分解。但是我希望它只打印复合不超过循环的第三个打印语句。该程序对于大型复合材料的因式分解非常快,但对于大型素数来说却很慢。

例如 3 个这样的打印:

3的因数是: 1、 3

如果我输入 2047,它会这样打印:

2047的因数是: 1、 23, 89, 2047

但是我希望它最多显示 89。这是代码:

    import math
    while True:
        def print_factors(x):
           print("The factors of",x,"are:")
           for i in range(1,x+1):
               if x % i == 0:
                   print(i)



        p = int(input('Enter a prime number and if the output is 1 and itself its prime: '))


        k = ((p**2*2))
        l = (((pow(2, k + 1, 2 * k) - 1) % (2 * k)))
        f = (k//2//p)
        print_factors(f)

【问题讨论】:

    标签: python loops for-loop printing calculation


    【解决方案1】:

    我在 python io 论坛上的 Gribouillis 的帮助下弄清楚了,但素数仍然打印,但截止值低于第 4 个输出。您可以生成因子并对迭代器进行切片!

        import itertools as itt
        while True: 
            def gen_factors(x):
                for i in range(1, x + 1):
                    if x % i == 0:
                        yield i
    
            def print_factors(x, maxcnt=None):
                g = gen_factors(x)
                if maxcnt is not None:
                    g = itt.islice(g, 0, maxcnt)
                for p in g:
                    print(p)
            p = int(input('Enter a prime number and if the output is 1 and itself 
            its prime: '))
            p = (2**p-1)
            k = ((p**2*2))
            f = (k//2//p)
            if __name__ == '__main__':
                 print_factors(p, 3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2021-03-01
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      相关资源
      最近更新 更多