title: Largest prime factor of a number in Java
body: <p>I am trying to find the Largest prime factor of a number while solving this problem <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler003" rel="nofollow">here</a>. I think that I am doing everything right, however one of the test case (#2) is failing and I can't think of any corner case where it might fail. Here's my code, please have a look and try to spot something.</p>
  
  <pre><code>public class ProblemThree
  {
      public static void main(String[] args)
      {
          Scanner scanner = new Scanner(System.in);
          int T = scanner.nextInt();
          for (int i = 0; i &lt; T; i++)
          {
              System.out.println(largestPrime(scanner.nextLong()));
          }
      }
  
      private static long largestPrime(long n)
      {
          while (n % 2 == 0)
          {
              n = n / 2;  // remove all the multiples of 2
          }
          while (n % 3 == 0)
          {
              n = n / 3; // remove all the multiples of 2
          }
  
          // remove multiples of prime numbers other than 2 and 3
          while (n &gt;= 5)
          {
              boolean isDivisionComplete = true;
              for (long i = 5; i &lt; Math.ceil(Math.sqrt(n)); i++)
              {
                  if (n % i == 0)
                  {
                      n = n / i;
                      isDivisionComplete = false;
                      break;
                  }
              }
              if (isDivisionComplete)
              {
                  break;
              }
          }
          return n;
      }
  }
  </code></pre>
  
  <p>Basically, what I am doing is:</p>
  
  <pre><code>Largest_Prime(n):
  1. Repeatedly divide the no by any small number, say x where 0 &lt; x &lt; sqrt(n).
  2. Then set n = n/x and repeat steps 1 and 2 until there is no such x that divides n.
  3  Return n.
  </code></pre>