Reputation: 43
I am not able to meet all the conditions of prime factors of a number so that I find the correct sum.
int sumPrime(number){
int counter;
int sum=0;
for(counter=2;counter<=(number/2);counter++){
if(number%counter==0){
sum=counter;
counter++;
sum+=counter;
}
return sum;
}
}
Upvotes: 0
Views: 18944
Reputation: 7
let n = 22;
let sum = 0;
function sumOfPrimeFactors(n) {
// Write your code here
if(n === 2){
return true;
}
if(n < 2 || isNaN(n) || (n%2===0)){
return false;
}
for(let i = 3; i < n; i++){
if(n%i === 0){
return false;
}
}
return true;
}
for(let i = 0; i <= n; i++){
if(sumOfPrimeFactors(i) === true){
if(n % i === 0){
sum += i;
}
}
}
console.log(`The sum of the prime factors in 91 is: ${sum}`)
Upvotes: 0
Reputation: 692
An efficient algorithm to find the prime factors
Code:
#include <stdio.h>
#include <math.h>
int sumPrime(int n) {
int sum = 0;
printf ("%6d: ", n);
// find all powers of 2
while (n%2 == 0) {
printf("%d+", 2);
n /= 2;
sum += 2;
}
// checking for factors up to sqrt(n) is sufficient
for (int i = 3; i <= sqrt(n); i += 2) {
// find all powers of i
while (n%i == 0) {
printf("%d+", i);
n /= i;
sum += i;
}
}
// n is prime at this point
if (n > 2) {
printf ("%d", n);
sum += n;
}
printf (" = %d\n", sum);
return sum;
}
void main() {
sumPrime(226);
sumPrime(39);
sumPrime(775);
}
Output:
226: 2+113 = 115
39: 3+13 = 16
775: 5+5+31 = 41
Upvotes: 0
Reputation: 122
#include <stdio.h>
int main(){
printf("sum is%i",sumCount(12));
return 0;
}
int sumCount(int number){
int count,sum=0;
for(count=2;count<number;count++){
if(isPrime(count)==1){
printf("%i \n",count);
sum+=count;
}
}
return sum;
}
int isPrime(int number){
int i;
for (i=2;i<=number/2 ;i++){
if(number%i==0){
return 0;
}
}
return 1;
}
Upvotes: 1
Reputation: 1957
I think the code is self explanatory. It works for number >= 2
.
int sumPrime(int number){
int factor = 2;
int sum=0;
while(1 != number){ //Repeat the loop till number becomes 1.
if(number%factor==0){ //Check if factor divides the number.
number /= factor; //If yes, update the number.
sum+=factor; //Add factor to sum.
printf("Factor [%d]\n", factor);
continue;
}
factor++; //If the current number is not a factor, check the next number.
}
printf("Sum [%d]\n", sum);
return sum;
}
Output for 12:
Factor [2]
Factor [2]
Factor [3]
Sum [7]
Upvotes: 2