Python Challenge - Sum of Prime Factors

This community-built FAQ covers the “Sum of Prime Factors” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge Sum of Prime Factors

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

def prime_finder(n):
prime=[2]
for x in range(3,n+1):
tog = True
for y in range(2,x):
if x % y == 0:
tog = False
if tog:
prime.append(x)

return prime
def sum_of_prime_factors(n):
alist =
for x in prime_finder(n):
if n % x == 0:
alist.append(x)

return sum(alist)

def prime_finder(n): # Write your code here asdlkj= [] if n == 0 or n==1: return asdlkj for i in range (2,n+1): if i % 2 == 0: if i==2: asdlkj.append(i) elif i% 3== 0: if i==3: asdlkj.append(i) elif i% 5== 0: if i==5: asdlkj.append(i) elif i% 7== 0: if i==7: asdlkj.append(i) else: asdlkj.append(i) return asdlkj def sum_of_prime_factors(n): # Write your code here primes = prime_finder(n) factors = [] for i in range(len(primes)): if n % primes[i] == 0: factors.append(primes[i]) return sum(factors) print(sum_of_prime_factors(91))
def sum_of_prime_factors(n): # Getting all primes in range(2,n) primes =[2] for num in range(3,n+1): aux = [] for p in primes: aux.append(num%p) if 0 in aux: next else: primes.append(num) n_prime_factors = [] #Determine factors of n in primes list for p in primes: if n%p == 0: n_prime_factors.append(p) return(sum(n_prime_factors)) print(sum_of_prime_factors(91))
def sum_of_prime_factors(n) : #def sum_of_prime_factors(n) : #Creating list to store all denominators of n denominator = [] #Creating list to store factor factor = [] #Creating list to store prime number prime_number = [] #Creating list to store denominator2 denominator2 = [] #Accessing all denominators by using for range loop methode for denom in range(2,n+1) : denominator.append(denom) #Taking only denom that generate mod 0 for element in denominator : process = n % element if process == 0 : factor.append(element) #Accessing element of list "factor" for ele in factor : count = 0 if ele == 2 : prime_number.append(ele) else : for num in range(2,ele) : processes = ele % num if processes == 0 : break else : count += 1 if count < len(range(2,ele)) : continue else : prime_number.append(ele) total_of_prime_number = sum(prime_number) return total_of_prime_number print(sum_of_prime_factors(91))
def prime_factors(num): for x in range(2,num+1): if num%x == 0: #returns a list of factors that are prime if x == num: return [x] #by recursively going through each factor return prime_factors(x) + prime_factors(num//x) def sum_of_prime_factors(num, added = []): return sum(set(prime_factors(num))) #set to get rid of duplicates
# Find primes by sieve of Eratosthenes def find_primes(n): numbers = [n for n in range(2, n+1)] for i in range(int(len(numbers) - 1)): n = numbers[i] if n != -1: # Mark multiples as -1 and remove them afterwards for j in range(i+n, len(numbers), n): numbers[j] = -1 numbers.sort() if numbers.count(2) < 1: return [] else: return numbers[numbers.index(2):] ''' Create list of primes [:n] and check for each if they divide n. If yes add them to the sum once. ''' def sum_of_prime_factors(n): primes = find_primes(n) sum = 0 for p in primes: if n%p == 0 and n > 1: n /= p sum += p return sum print(sum_of_prime_factors(91)) print(sum_of_prime_factors(8))

I did stuff similar to the others above, but I tried to keep the number of lists in the code as low as possible.
I had a separate function to check if a number is prime (and I didn’t check if there are factors larger than the square root of the number being tested, because it’s unnecessary).
Here’s the classic version (Sieve of Eratosthenes), similar to the previous posts.

classic version
from math import sqrt, floor, ceil

def isPrime(x):
  if x < 2:
    return False;
  elif x < 4:
    return True;
  end = sqrt(x)
  j = 2
  while j <= end:
    if (x % j) == 0:
      return False
    j += 1
  return True


def sum_of_prime_factors(n):
  total = 0
  for i in range(2, n + 1):
    # if i is a factor of n, and i is prime, add it to total
    if (n % i) == 0: 
      if isPrime(i):
        total += i  
        #print(i, end=" + ")
  #print("=", total, "for n =", n) 
  return total

I also did a version using the prime factorization of a number.
(The algorithm simulates factoring and storing the factors).
It’s faster than the other version for larger numbers, but it requires more memory.

code using prime factorization
from math import sqrt, floor, ceil

def isPrime(x):
  if x < 2:
    return False;
  elif x < 4:
    return True;
  end = floor(sqrt(x))
  j = 2
  while(j <= end):
    if (x % j) == 0:
      return False
    j += 1
  return True

def get_next_prime(y):
  if y < 2:
    return 2
  y += 1
  while not isPrime(y):
    y += 1
  return y

def get_prime_factorization(n):
  if (n < 2): 
    return 1
  x = n
  primes = dict()
  p = 2  # starting prime number
  while x >= 2 and p <= n:
    while (x % p) == 0:
      # each time prime p is a factor, increase its entry 
      if p in primes:
        primes[p] += 1
      else:
        primes[p] = 1
      # make x the number remaining when p is factored out of x
      x = x // p
      # end of inner loop
    p = get_next_prime(p)
    # end of outer loop
  return primes

sum_of_prime_factors = lambda n: sum( get_prime_factorization(n).keys() )

The overall steps used are similar to the ones in @jp440’s code and in @biggbosss’s code.

def sum_of_prime_factors(n):
lst=
for x in range(1,n+1):
count=0
for w in range(1,x+1):
if x%w==0:
count+=1
if count==2 and n%x==0:
lst.append(x)
return sum(lst)

print(sum_of_prime_factors(91))

Did that pass all tests? It was recently pointed out to me that each prime be unique in the sum. In other words, we’re summing up a set, not a list.

>>> l = [1,2,1,2,4,3,4,3]
>>> sum(list(set(l)))
10
1 Like
def sum_of_prime_factors(n, u=1):
  def is_prime(x):
    if x < 2: return False
    for h in range(2, int(x ** 0.5) + 1):
      if x % h == 0: return False
    return True
  def get_factors(a):
    if a < 2: return [0]
    if a % 1 > 0: a = int(a)
    if is_prime(a): return [a]
    factors = []
    for x in range(2, a // 2):
      if is_prime(x):
        while a % x == 0:
          if a % x == 0:
            factors.append(x)
          a /= x
    print (factors)
    return factors
  return sum(set(get_factors(n))) if u else sum(get_factors(n))

print(sum_of_prime_factors(91))
print(sum_of_prime_factors(191))
print(sum_of_prime_factors(88))
print(sum_of_prime_factors(88, 0))
print(sum_of_prime_factors(216))
print(sum_of_prime_factors(216, 0))
[7, 13]
20
191
[2, 2, 2, 11]
13
[2, 2, 2, 11]
17
[2, 2, 2, 3, 3, 3]
5
[2, 2, 2, 3, 3, 3]
15

For the record, all tests passed.

1 Like

Thank you for reviewing my codes.
I apologize for how messy my code is being displayed. I’m unsure how to directly post the code from the code challenges.
sum-of-prime

This is how my codes look like.
I understood your comment.
As far as I’ve checked, there’s unlikely to be repeatable x values to be appended to the list lst.
Would appreciate if you would check my codes again.

1 Like

Have you run the tests?

Ah yes, I’ve run the tests.

print(sum_of_prime_factors(91))
[7,13]
20
print(sum_of_prime_factors(191))
[191]
191
print(sum_of_prime_factors(88))
[2,11]
13
print(sum_of_prime_factors(216))
[2,3]
5
print(sum_of_prime_factors(2))
[2]
2
print(sum_of_prime_factors(-1))

0

1 Like

Looks like you should have passed all tests in the challenge LE; is that the case also? If so, there is nothing to check.

If you’re referring to the Code Challenges: Sum of Prime Factors, Yes, the tests passed. Are there other challenge activities I should be aware of?

Thank you

1 Like

You found this one so must have access to all the rest. There are similar challenges in other languages, too.

code_challenges_link

1 Like

TBH, I’m still scratching my head why both loops start with 1. Obviously it doesn’t raise a fly in the ointment, but I just don’t see the logic. Can you please explain?

1 Like

Inline code is one backtick on the left, and one on the right. Code block samples are, three backticks, optional language name in lowercase, line break, code block, line break, three backticks.

This sentence has `inline code` embedded in the prose.

css
```css

body {
  font-size: 100%;
  color: black;
  background-color: white;
}

```

1 Like

ah, yes. I should have started with 2 instead. I just reused my code that I have completed from the code challenges: Prime Number Finder that involves to return prime numbers from 1 to n (inclusive).

Thank you for pointing that out for me.

1 Like