I have started learning to code in Java and decided I would use the Project Euler site to give me little tasks to try and complete with each bit of new coding I learn. So I came across Problem 3:
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
I thought about the problem and researched many different theories about prime numbers and how they can be found via various different calculations (Sieve of Eratosthenes being an example) and the solution I conjured up was to test numbers from 2 --> n and see if they were a prime number, if they were then I would divide the Tn variable (in this case 600851475143) by the newly discovered prime number and see if it was a factor. If it was, I would assign it to the variable Hp (Highest Prime number) and at the end of the program I would output Hp to the console to give my result.
Here is my code:
public class Largest_Prime_Factor_NEW_SOLUTION {
static long Tn = 600851475143L;
static long Hp = 0;
static boolean isPrime = false;
public static void main(String[] args) {
for (long i=2; i<Tn; i++) {
System.out.println("TESTING NUMBER " + i);
for (long k=2; k < i; k++) {
if (i % k == 0) {
System.out.println(i + " IS NOT A PRIME");
break;
} else if (k + 1 == i) {
isPrime = true;
}
}
if (isPrime) {
System.out.println(i + " IS A PRIME");
if (Tn % i == 0) {
System.out.println(Tn + " IS DIVISIBLE BY " + i);
Hp = i;
} else {
System.out.println(Tn + " IS NOT DIVISIBLE BY " + i);
}
}
isPrime = false;
}
System.out.println("THE HIGHEST PRIME NUMBER OF " + Tn + " IS " + Hp);
}
}
Now I know that this code is very inefficient and for just starting I have managed to condense it from where I began (there were loops everywhere!) but what I am is asking is, how can I improve this? It's eating away at me because everything I research contradicts what others would do and it's very confusing. I have tried the sieve method but i understand that a boolean array can only be an int array and never a long array?
I understand that when beginning to code I will be limited to what knowledge I can use, but just out of interest, I am keen to see what the final solution would be.