Java Challenge - Sum of Prime Factors

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

Top Discussions on the Java 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 () 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.

You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? 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

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!

``````import java.util.*;

public class SumOfPrimeFactors {
public static void main(String[] args) {
System.out.println(sumOfPrimeFactors(100));
}

/**
* Finds all the prime factors of an int
* and adds them together.  Edge cases are when
* the number itself is prime, and when the input is 1.
*/
public static int sumOfPrimeFactors(int n) {
ArrayList<Integer> primeFactors = new ArrayList<>();

// First find the prime factors.
for (int i = 2; i <= n / 2; i++) {
if (n%i ==0) {
if (isPrime(i)) {
}
}
}

int sumOfPrimeFactors = 0;

// This if statement handles both edge cases.
if (primeFactors.isEmpty() && n > 1) {
sumOfPrimeFactors = n;
}
else {
for (int i : primeFactors) {
sumOfPrimeFactors += i;
}
}

return sumOfPrimeFactors;
}

/**
* Returns true if the int is a prime number,
* false otherwise.
*/
public static boolean isPrime(int n) {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

}
``````

That went smoothly:

``````import java.util.*;

public class SumOfPrimeFactors {
public static void main(String[] args) {
System.out.println(sumOfPrimeFactors(1025));
}

public static int sumOfPrimeFactors(int n) {
int returnValue = 0;

for(int i = 2; i <= n;++i){
while(n%i==0){
returnValue+=i;
n/=i;
}
}
return returnValue;
}
}
``````