牛客网在线编程:素数对

题目描述:

给定一个正整数,编写程序计算有多少对质数的和等于输入的这个正整数,并输出结果。输入值小于1000。
如,输入为10, 程序应该输出结果为2。(共有两对质数的和为10,分别为(5,5),(3,7))
输入描述:
输入包括一个整数n,(3 ≤ n < 1000)
输出描述:
输出对数
示例1
输入

10
输出

2

思路:

思路:判断素数,只需要判断2-sqrt(n)即可
两个数的和,一个数从2-n/2,另一个从n/2-n-2即可
先判断是否满足和等于给定的数,再判断是否为素数

 1 import java.util.*;
 2 public class Sushudui {
 3     public static boolean isPrime (int n){
 4         for(int i = 2;i<=Math.sqrt(n);i++){
 5             if(n%i==0) return false;
 6         }
 7         return true;
 8     }
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         Scanner sc = new Scanner(System.in);
12         int n = sc.nextInt();
13         int count = 0;
14 //        for(int i = 2; i <= n/2;i++){
15 //            for(int j = n/2 ;j<=n-2;j++){
16 //                if(i+j==n){
17 //                    if(isPrime(i)&&isPrime(j)){
18 //                        count++;
19 //                        //System.out.println(i);
20 //                        //System.out.println(j);
21 //                    }
22 //                }
23 //            }
24 //        }
25         for(int i = 2; i <= n/2; i++){
26             for(int j = n; j >=i;j--){
27                 if(i+j==n){
28                     if(isPrime(i)&&isPrime(j)){
29                         count++;
30                     }
31                 }
32             }
33         }
34         System.out.println(count);
35     }
36 
37 }
原文地址:https://www.cnblogs.com/zlz099/p/8549701.html