Search code examples
javaprime-factoring

Finding the prime factor of a Long number using Java


public class prime
{
   public static void main(String[] args)
    {
     long thing = 600851475143L;
     for(long i = 300425737571L ; i == 0 ; i-- ){
     if (thing % i == 0)
     {
       long answer = i;
       System.out.println(answer);
       break;
     }
     }

    }

}

This is the code I currently have, however I have been running it in DrJava for a few minutes and it has returned no results. I'm guessing there are roughly a million ways my code can be optimised though ; would anyone be able to give me some tips ?

Trying to work through a few programming problems today and this one is causing me some trouble.

Thanks a lot :)


Solution

  • You only need iterate down to sqrt(thing), though.

    And in general it's going to be quicker to iterate starting from 2, since half the numbers will have a factor of two (and 1/3 a factor of 3 etc.

    You're also breaking only on the first factor so will miss any others

     long thing = 600851475143L;
     for(long i = 0; i < 300425737571L ; i++ ){
         if (i * i > thing) {
           break;
         }
         if (thing % i == 0) {
           long answer = i;
           System.out.println(answer);
           break;
         }
     }
    
    • more sophisticated methods are available as aioobe says