Note that there are some explanatory texts on larger screens.

plurals
  1. POLargest prime factor program takes aaaages - Java
    primarykey
    data
    text
    <p>So this is problem 3 from project Euler. For those who don't know, I have to find out the largest prime factor of 600851475143. I have the below code:</p> <pre><code>import java.lang.Math; // 600851475143 public class LargestPrimeFactor { public static void main(String[] stuff) { long num = getLong("What number do you want to analyse? "); long[] primes = primeGenerator(num); long result = 0; for(int i = 0; i &lt; primes.length; i++) { boolean modulo2 = num % primes[i] == 0; if(modulo2) { result = primes[i]; } } System.out.println(result); } public static long[] primeGenerator(long limit) { int aindex = 0; long[] ps = new long[primeCount(limit)]; for(long i = 2; i &lt; limit + 1; i++) { if(primeCheck(i)) { ps[aindex] = i; aindex++; } } return ps; } public static boolean primeCheck(long num) { boolean r = false; if(num == 2 || num == 3) { return true; } else if(num == 1) { return false; } for(long i = 2; i &lt; Math.sqrt(num); i++) { boolean modulo = num % i == 0; if(modulo) { r = false; break; } else if(Math.sqrt(num) &lt; i + 1 &amp;&amp; !modulo) { r = true; break; } } return r; } public static int primeCount(long limit) { int count = 0; if(limit == 1 || limit == 2) { return 0; } for(long i = 2; i &lt;= limit; i++) { if(primeCheck(i)) { count++; } } return count; } public static long getLong(String prompt) { System.out.print(prompt + " "); long mrlong = input.nextLong(); input.nextLine(); return mrlong; } } </code></pre> <p>But when I test the program with something (a lot) smaller than 600851475143, like 100000000, then the program takes its time - in fact, 100000000 has taken 20 minutes so far and is still going. I've obviously got the wrong approach here (and yes, the program <em>does</em> work, I tried it out with smaller numbers). Can anyone suggest a less exhaustive way?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload