- package com.yuxi.day0923;
- public class Test4 {
- /*
- * 0<N<M<=100000 求第N个素数到第M个素数之间所有素数的和 包括N和M
- */
- public static void main(String[] args) {
- System.out.println(theNumPrimeSum(4,56767));
- }
- // 求素数的方法
- public static boolean boolPrime(int n) {
- boolean flag = false;
- if (n == 1) {
- return flag;
- } else if (n == 2) {
- flag = true;
- } else {
- int num = 2;
- while (true) {
- if (n % num == 0) {
- break;
- } else if (num > Math.sqrt(n)) {
- flag = true;
- break;
- }
- num++;
- }
- }
- return flag;
- }
- // 求素数和的方法并打印出结果
- public static void sumPrime(int n, int m) {
- int sum = 0;
- if (n > m) {
- int temp = n;
- n = m;
- m = temp;
- }
- if (n > 0 && n <= 200) {
- for (int i = n; i <= m; i++) {
- if (boolPrime(i)) {
- sum += i;
- }
- }
- System.out.println(n + "与" + m + "之间的质数和是" + sum);
- } else
- System.out.println("你的数据有误");
- }
- //求出第num个质数是什么
- public static int theNumPrime(int num) {
- int thenum = 0;
- int number = 0;
- int n = 2;
- while (true) {
- if (boolPrime(n)) {
- number++;
- if (num == number) {
- thenum = n;
- break;
- }
- }
- n++;
- }
- return thenum;
- }
- //求第num1到num2这间的质数和
- public static int theNumPrimeSum(int num1, int num2) {
- int sum = 0;
- int a = theNumPrime(num1);
- int b = theNumPrime(num2);
- for (int i = a; i <= b; i++) {
- if (boolPrime(i)) {
- sum += i;
- }
- }
- return sum;
- }
- }
复制代码
|
|