Here is my code:
public class LargestPrimeFactor {
/**
* @param args the command line arguments
*/
public static boolean isPrime(long x){
for (int y=2; y<x; y++){
if (x%y==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println("Find out the largest prime factor of 600851475143");
long num=600851475143L;
int largest=0;
int y=0;
for (int x=2; x<num; x++){
if (num%x==0&&isPrime(x)==true){
System.out.println(x);
}
}
System.out.println(largest);
}
Here is the output:
Find out the largest prime factor of 600851475143
71
839
1471
6857
-716151937
-408464633
-87625999
-10086647
-5753023
-1234169
-486847
-104441
-59569
-6857
-1471
-839
-71
-1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at largestprimefactor.LargestPrimeFactor.main(LargestPrimeFactor.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 minutes 10 seconds)
How do I print out the largest number? and why does the output show negative numbers when "x" is supposed to be constantly increasing, never decreasing?
UPDATE
Here is my edited code:
public static boolean isPrime(long x){
for (int y=2; y<x; y++){
if (x%y==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println("Find out the largest prime factor of 600851475143");
long num=600851475143L;
long largest=0;
int y=0;
for (long x=2; x<num/2; x++){
if (num%x==0&&isPrime(x)==true){
System.out.println(x);
if (largest<x){
largest=x;
}
}
}
System.out.println(largest);
}
Here is the new output
Find out the largest prime factor of 600851475143
71
839
1471
6857
0
BUILD SUCCESSFUL (total time: 318 minutes 31 seconds)
How do I get the final answer to be printed out as "6857" rather than "0"? Also, if you notice, the run time for the program was a little over 5 hours. How do I speed up this process?