So, I'm trying to find the largest prime factor of 600851475143. I have a simple method that finds the largest one currently which is this:
private static void findPrimeFactors(long num) {
ArrayList<Long> list = new ArrayList<Long>();
for (long i = 1; i <= num; i++) {
int lol = 0;
for (int a = 1; a < i; a++) {
if (i % a == 0) {
lol++;
}
}
if (lol < 2) {
if (!list.isEmpty())
list.remove(list.size() - 1);
list.add(i);
}
}
System.out.println(list.get(list.size() - 1));
}
Excuse me for my bad programming, I'm still learning. I figured that removed a lot of the entries from the list would cut down on the time to calculate it, so I removed the last entry unless it's the last one. I can do it with 100L which outputs the following:
97
Done in 1.0 milliseconds (0.001 seconds) (0.0625622 nano seconds)
And 20,000:
19997
Done in 1774.0 milliseconds (1.774 seconds) (177.3702774 nano seconds)
As you can see, it takes quite a bit longer to find it in a bigger number. Now I'm supposed to find the number I'm looking for in 600851475143, so I can say it's going to take a while to do. I'm wondering if their is any faster way to calculate this? This is all of my code:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
try {
long num = 600851475143L;
long time = System.currentTimeMillis();
long timeNano = System.nanoTime();
findPrimeFactors(20000);
double finishTime = System.currentTimeMillis() - time;
double finishTimeNano = System.nanoTime() - timeNano;
System.out.println("Done in " + finishTime + " milliseconds (" + ((finishTime) / 1000) + " seconds)" + " (" + finishTimeNano / 10000000 + " nano seconds)");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void findPrimeFactors(long num) {
ArrayList<Long> list = new ArrayList<Long>();
for (long i = 1; i <= num; i++) {
int lol = 0;
for (int a = 1; a < i; a++) {
if (i % a == 0) {
lol++;
}
}
if (lol < 2) {
if (!list.isEmpty())
list.remove(list.size() - 1);
list.add(i);
}
}
System.out.println(list.get(list.size() - 1));
}
}
Any tips on how to make this much faster is appreciated! Many of you may know that I'm doing this from Project Euler.