简体   繁体   中英

Prime factorization of a big number

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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