Prime factorization of a big number

时光毁灭记忆、已成空白 提交于 2020-02-05 06:06:04

问题


I'm trying to create a program for prime factorization of a number and this is the code I came up with.

def primeFactors(n):
    l=[]
    ss=0
    for i in range(2,n,1):
    #checking for prime
        t=0
        for j in range(2,i):
            if(i==2):
                continue
            if(i%j==0):
                t=t+1   
        if(t>0):
            continue
        else:
            if(n==0):
                break
            else:
                print(i)
                if(n%i==0):
                    n=n//i
                    ss=ss+1
                    i=i-1
                if(n%i!=0 and ss>0):
                    l.append(i)
                    l.append(ss)
                    ss=0
                else:
                    continue
    q=""
    for i in range(0,len(l),2):
        q=q+"("+str(l[i])+"**"+str(l[i+1])+")"
    return q

The working of the code is as follows:

  1. It checks whether the number in the outer loop is a prime or not.
  2. If it is a prime, then it proceeds to check whether division of the number with n would yield a remainder of 0 or not, if it does, divide it.
  3. Increment ss which is the number of times the prime number would be used in the whole factorisation. Also, decrement the value of i so that when it increments at the end of the loop, it remains the same to check again whether i can divide n or not.
  4. If it cannot divide and ss (number of times i could divide) is more than 0 then we append it to a list.

I am getting timeout errors in this and cannot figure out how to go about fixing it.

Any help is appreciated


回答1:


You can increase i only if i does not divide n. Also, you can just check until the square root of n, since if i divides n, then i <= sqrt(n).

Example:

import math

def prime_factors(n):

    i, factors = 2, []

    while n > 1 and i <= int(math.sqrt(n)):
        if n%i == 0:
            n/=i
            factors.append(i)
        else:
            i+=1

    if n > 1:
        factors.append(int(n))

    return factors


>>> prime_factors(64)
[2, 2, 2, 2, 2, 2]
>>> prime_factors(28)
[2, 2, 7]
>>> prime_factors(31)
[31]

Note. You don't need to check if i is a prime number. i cannot be not prime, since if i were not prime, then there would exist a j < i that divides i with j being prime. Since i goes from 2 to sqrt(n), it would have met before in the loop.



来源:https://stackoverflow.com/questions/59961109/prime-factorization-of-a-big-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!