Jordan
0
Q:

prime factorization python

import math


def primeFactors(n):
    # no of even divisibility
    while n % 2 == 0:
        print(2)
        n = n / 2
    # n reduces to become odd
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        # while i divides n
        while n % i == 0:
            print(i)
            n = n / i
    # if n is a prime
    if n > 2:
        print(n)


primeFactors(256)
2
# There is no quick way to calculate the prime factors of a number.
# In fact, prime factorization is so famously hard that it's what puts the "asymmetric" in asymmetric RSA encryption.
# That being said, it can be sped up a little bit by using divisibility rules, like checking if the sum of the digits is divisible by 3.

def factors(num):
        ps = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149] # Primes from https://primes.utm.edu/lists/small/10000.txt. Primes can also be generated by iterating through numbers and checking for factors, or by using a probabilistic test like Rabin-Miller.
        pdict = {}
        for p in ps:
                if p <= num:
                        while (num / p).is_integer():
                                if str(p) in pdict:
                                        pdict[str(p)] += 1
                                else:
                                        pdict[str(p)] = 1
                                num /= p
                if num == 1: break
        return pdict

# Returns a dictionary in the form {"base": "exponent"}
1
# Python program to print prime factors 
  
import math 
  
# A function to print all prime factors of  
# a given number n 
def primeFactors(n): 
      
    # Print the number of two's that divide n 
    while n % 2 == 0: 
        print 2, 
        n = n / 2
          
    # n must be odd at this point 
    # so a skip of 2 ( i = i + 2) can be used 
    for i in range(3,int(math.sqrt(n))+1,2): 
          
        # while i divides n , print i ad divide n 
        while n % i== 0: 
            print i, 
            n = n / i 
              
    # Condition if n is a prime 
    # number greater than 2 
    if n > 2: 
        print n 
          
# Driver Program to test above function 
  
n = 315
primeFactors(n) 
  
# This code is contributed by Harshit Agrawal 
0

New to Communities?

Join the community