0

i am new to python and i am trying to find the efficient way of finding the prime factors of a number using python. for problem reference - https://projecteuler.net/problem=3

generally, what i did is:-

  1. first my logic was to define a function (i.e is_prime( ) ) which takes list of factors and checks which are prime and returns the list of nums which are prime. for which i created a prime = [ ] list to store all primes

  2. now i created a function named ( i.e prime_factor( ) ) which actually extracts all factors and of that number and stores them in list i.e factors = [ ].

  3. finally i used is_prime( ) function on my "factors" list to seperate out all primes but i failed to do so.

because the result i obtained when i entered input(13195) then as output i got - [5, 7, 13, 29, 35, 65] where 35 and 65 are not prime as 7 and 5 are there factors.

import math as m
def prime_factors(n):
    factors = []
    for i in range(2,int(m.sqrt(n/2))+1):
        if n % i == 0:
            factors.append(i)
    return (is_prime(factors))

def is_prime(nums): # this functions takes in a list of nums and return list of only those nums which are prime.
    prime = [] 
    for i in nums:
        if i > 1:
            for j in range(2,int(i)+ 1):
                if i % j == 0:
                    break
                prime.append(i)
                break
    return prime

print(prime_factors(13195))

thanks in advance!! hope i could learn something new and correct myself from your responses. Thank you...

Roney Moon
  • 11
  • 1

0 Answers0