title: Prime Numbers in Java - Algorithms
body: <p>I have started learning to code in Java and decided I would use the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> site to give me little tasks to try and complete with each bit of new coding I learn. So I came across <a href="https://projecteuler.net/problem=3" rel="nofollow">Problem 3</a>:</p>
  
  <p>The prime factors of 13195 are 5, 7, 13 and 29.
  What is the largest prime factor of the number 600851475143 ?</p>
  
  <p>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.</p>
  
  <p>Here is my code:</p>
  
  <pre><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&lt;Tn; i++) {
              System.out.println("TESTING NUMBER " + i);
              for (long k=2; k &lt; 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);
      }
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>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.</p>