问题描述
输入一个自然数n,求小于等于n的素数之和
样例输入
2
样例输出
2
数据规模和约定
测试样例保证 2 <= n <= 2,000,000
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 |
package adv184; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); boolean[] prime = new boolean[n+1]; in.close(); setPrime(prime); long sum = 0; for (int i = 2; i < prime.length; i++) { if (prime[i]) { sum += i; } } System.out.println(sum); } private static void setPrime(boolean[] prime) { for (int i = 2; i < prime.length; i++) { prime[i] = true; } for (int i = 2; i < prime.length; i++) { for (int j = 2; i * j < prime.length; j++) { prime[i * j] = false; } } } } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼