Java

for

Modulo

public class Program {
public static boolean isPrime(int candidate) {
*// All even numbers except 2 are not primes.*
if ((candidate & 1) == 0) {
if (candidate == 2) { *// Two is prime.*
return true;
} else {
return false;
}
}
*// Search for prime numbers of the candidate.*
*// ... Primes are odd, smaller than the candidate.*
*// ... And a modulo division returns 0.*
for (int i = 3; (i * i) <= candidate; i += 2) {
if ((candidate % i) == 0) {
return false;
}
}
return candidate != 1;
}
public static void main(String[] args) {
*// Test first 100 numbers for primes.*
for (int test = 0; test < 100; test++) {
if (isPrime(test)) {
System.out.println(test);
}
}
*// Test larger numbers.*
for (int test = 10000; test < 10100; test++) {
if (isPrime(test)) {
System.out.println(test);
}
}
}
}2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
10007
10009
10037
10039
10061
10067
10069
10079
10091
10093
10099

HashMap

import java.util.HashMap;
public class Program {
public static boolean isPrime(int candidate) {
*// This is the same method as described above.*
if ((candidate & 1) == 0) {
if (candidate == 2) {
return true;
} else {
return false;
}
}
for (int i = 3; (i * i) <= candidate; i += 2) {
if ((candidate % i) == 0) {
return false;
}
}
return candidate != 1;
}
static HashMap<Integer, Boolean> primes = new HashMap<>();
public static boolean isPrimeMemoized(int candidate) {
*// Try to use the HashMap to see if a number is a prime.*
if (primes.containsKey(candidate)) {
System.out.println(*"Memoized prime result"*);
return primes.get(candidate);
}
*// Record our prime status in the HashMap.*
boolean result = isPrime(candidate);
primes.put(candidate, result);
return result;
}
public static void main(String[] args) {
*// Detect prime numbers with memoized method.*
boolean value = isPrimeMemoized(10007);
System.out.println(value);
value = isPrimeMemoized(10007);
System.out.println(value);
}
}true
Memoized prime result
true

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Jan 20, 2024 (edit).