java - How can i shorten this algorithim for finding Prime Numbers? -
just wondering if me on this. code working possible shorten/remove unnecessary code algorithim while keeping method same? have taken out things don't need unsure if else can taken out.
thanks in advance!
public static void listprimes(int maxnum) { (int = 2; < maxnum; i++) { boolean isprime = true; (int j = 2; j <= math.sqrt(i); j++) { if (i > 1 && j < && % j == 0) { isprime = false; break; } } if (isprime) { system.out.println(i); } } }
ok, not shorten, rather speed up. note there more efficient methods finding prime numbers.
apart outputting value, math.sqrt(i)
expensive operation (as numbers start getting large, take increasingly greater percentage of processing time), may want consider putting variable before loop.
only 2 , uneven numbers prime, can hard-code 2 , skip numbers.
i > 1 && j < i
pointless mentioned.
shorten - replace isprime
checking j
.
public static void listprimes(int maxnum) { system.out.println(2); (int = 3; < maxnum; += 2) { int sqrti = (int)math.sqrt(i); int j; (j = 2; j <= sqrti; j++) if (i % j == 0) break; if (j == sqrti + 1) system.out.println(i); } }
Comments
Post a Comment