Home BOJ. Continuative sum of prime (1644)
Post
Cancel

BOJ. Continuative sum of prime (1644)

[Link] https://www.acmicpc.net/problem/1644


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int n = toi(br.readLine());
		ArrayList<Integer> al = getPrime(n);
		int left = 0, right = 0, size = al.size(), sum = 0, cnt = 0;
		while(left < size && right <= size) {
			if(sum < n) {
				if(right == size) break;
				sum += al.get(right++);
			} else if(sum == n) {
				cnt++;
				sum -= al.get(left++);
			} else {
				sum -= al.get(left++);
			}
		}
		print(cnt);
	}

	static ArrayList<Integer> getPrime(int n) {
		ArrayList<Integer> al = new ArrayList<>();
		for(int i = 2; i <= n; i++) {
			boolean prime = true;
			for(int e: al) {
				if(e > Math.sqrt(i)) break;
				if(i % e == 0) {
					prime = false;
					break;
				};
			}
			if(prime) al.add(i);
		}
		return al;
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.