지정한 범위 내에 있는 소수를 찾는 코드
static ArrayList<Integer> primes = new ArrayList<Integer>();
public static void main(String[] args) throws Exception {
getPrimes(100); // 2~100에서 소수를 찾는다.
System.out.println(primes);
}
public static void getPrimes(int end) {
boolean isPrime = true;
for(int i=2; i<=end; i++) {
for(int j=2; j<=Math.ceil(Math.sqrt(i)); j++) {
if(i != j && i % j == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
primes.add(i);
}
isPrime = true;
}
return;
}
'미역 > 자바' 카테고리의 다른 글
StringBuilder (0) | 2021.12.01 |
---|---|
그룹 합의 차이가 최소인 두 그룹으로 나누기 (0) | 2021.11.15 |
Comparable 과 Comparator (0) | 2021.11.02 |
그래프에서 DFS로 사이클 찾기 (0) | 2021.10.28 |
TreeSet과 Comparator (0) | 2021.10.25 |