Baekjoon Algorithm | Problem 2581: Primes
Source
https://www.acmicpc.net/problem/2581
Problem
Solve Baekjoon Online Judge problem 2581, Primes.
Input
Follow the input format and constraints given in the original problem statement.
Output
Print the answer required by the problem.
Sample Input 1
60 100
Sample Output 1
620 61
Sample Input 2
64 65
Sample Output 2
-1
Algorithm Classification
- Math
- Number Theory
- Primality Testing
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
int m = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
int sum = 0;
int min = Integer.MAX_VALUE;
for (int i = m; i <= n; i++) {
if (isPrime(i)) {
sum += i;
if (min > i) {
min = i;
}
}
}
if (sum == 0) {
System.out.println(-1);
} else {
System.out.println(sum);
System.out.println(min);
}
}
}
private static boolean isPrime(int num) {
if (num == 1)
return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}