Prime numbers have 2 factors only, 1 and itself. Factors are the numbers that can divide any given integer completely. There are certain observations regarding factors.
- 1 and the digit itself will always be the factor.
- Factors always come in pairs, for example, 1*60, 2*30, 3*20, etc
- The largest factor of any digit is the digit itself.
- 2nd largest factor will be N/2, the 3rd largest factor is N/3 and the 4th largest factor is N/4, and so on.
- Factors will always be less than the square root of the number
package org.wesome.dsalgo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SieveOfEratosthenes {
public static List<Integer> findAllPrime(int n) {
boolean prime[] = new boolean[n + 1];
List<Integer> primeNumbers = new ArrayList<>();
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
System.out.println(" p is prime = " + p + " updating all factors of p as false");
for (int i = p * p; i <= n; i += p) {
prime[i] = false;
}
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i] == true) {
System.out.print(i + " ");
primeNumbers.add(i);
}
}
System.out.println("primeNumbers = " + primeNumbers);
return primeNumbers;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
public class SieveOfEratosthenesTest {
@Test
void findAllPrimeTest1() {
List<Integer> primeNumbers = new ArrayList<>();
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
primeNumbers.add(7);
Assertions.assertTrue(primeNumbers.equals(SieveOfEratosthenes.findAllPrime(10)));
}
@Test
void findAllPrimeTest2() {
List<Integer> primeNumbers = new ArrayList<>();
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
primeNumbers.add(7);
primeNumbers.add(11);
primeNumbers.add(13);
primeNumbers.add(17);
primeNumbers.add(19);
primeNumbers.add(23);
primeNumbers.add(29);
primeNumbers.add(31);
primeNumbers.add(37);
primeNumbers.add(41);
primeNumbers.add(43);
primeNumbers.add(47);
primeNumbers.add(53);
primeNumbers.add(59);
primeNumbers.add(61);
primeNumbers.add(67);
primeNumbers.add(71);
primeNumbers.add(73);
primeNumbers.add(79);
primeNumbers.add(83);
primeNumbers.add(89);
primeNumbers.add(97);
Assertions.assertTrue(primeNumbers.equals(SieveOfEratosthenes.findAllPrime(100)));
}
}
plugins {
id 'java'
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}