Problem of the Day
A new programming or logic puzzle every Mon-Fri

Prime Summation

Today's objective is to write a function that takes in a number and returns the sum of all its prime factors. For example, if 10 were passed in then the function would return 7 (2 + 5 = 7). The number 1 is not considered prime.

Permalink: http://problemotd.com/problem/prime-summation/

Comments:

  • Karl - 10 years, 6 months ago

    Do you mean 210?

    3 and 7 aren't factors of 10 :P

    reply permalink

  • Max Burstein - 10 years, 6 months ago

    Whoops I messed up on that one. I updated the problem

    reply permalink

  • David - 10 years, 6 months ago

    I looked at the problem just in time to see your edits. Lucky me. _^

    reply permalink

  • Anonymous - 10 years, 6 months ago

    #python 2.7
    def sum_prime_factors(n):
        i = 2
        prime_factors = []
        while i * i <= n:
            if n % i:
                i = i + 1
            else:
                n = n / i
                if i not in prime_factors:
                    prime_factors.append(i)
        if n > 1:
            if n not in prime_factors:
                prime_factors.append(n)    
        s = 0
    
        for factor in prime_factors:
            s += factor
    
        return s
    

    reply permalink

  • Max Burstein - 10 years, 6 months ago

    Could always change prime_factors to a set to speed up look up time. Other then that it looks good. I like it.

    reply permalink

  • Alex - 10 years, 6 months ago

    function primeSum(number){
        var sum = 0;
        for(var i = 2; i < number; i++){
            if(number % i == 0){
                sum += i;
            }
        }
        return sum;
    }
    

    reply permalink

  • Mre64 - 10 years, 6 months ago

    perfectly simple, love it...

    reply permalink

  • bumbleguppy - 10 years, 6 months ago

    javascript

      function sum_O_Primes(val)
      {
         var result = 0;
         for(var i = 2, mid = Math.ceil(val / 2); i <= mid; i++){
            if(val % i === 0 && isPrime(i)){
               result += i;
            }
         }  
    
         return result;
    
         function isPrime(num){
            if(num <= 1) return false;
            if(num === 2 || num === 3) return true;
            if(num % 2 === 0 || num % 3 === 0) return false;
    
            var squareRoot = Math.sqrt(num);
    
            for(var i = 3; i <= squareRoot; i+=2){
               if(num % i === 0) return false;
            }
            return true;
         }
      }
    
      console.log(sum_O_Primes(10));
    

    reply permalink

Content curated by @MaxBurstein