验证哥德巴赫猜想
输入一个大于6的偶数,请输出这个偶数能被分解为哪两个质数的和。
如10=3+7 12=5+7;
要求:两个人一组完成。一个人负责把一个整数n拆分成两个整数的和,另一个人负责写一个函数,判断某一个整数a是否是质数。
代码如下:
package com.qf.t0.HWork;
import java.util.Scanner;
public class TestMyWork {
//程序员A,调用工具方法
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个大于6的偶数!");
int n = input.nextInt();
checkGoldBach(n , new asIsPrime() );
}
//(2)验证哥德巴赫猜想(工具)
public static void checkGoldBach(int n , MathTool tool){
if(n < 6 || n % 2!= 0){
System.out.println("输入错误,请重新输入");
}
for (int i = 3; i < n / 2; i += 2) {
int j = n - i;
//判断两个数均为质数
if (tool.isPrime(i) && tool.isPrime(j)) {
//打印输出结果
System.out.println(n + " = " + i + " + " + j);
}
}
}
}
//(接口)约定:指定标准(隔离)
interface MathTool{
public abstract boolean isPrime(int n);
}
//程序员A,写个实现类
class asIsPrime implements MathTool{
@Override
public boolean isPrime(int a) {
for (int j = 2; j < a - 1; j++) {
if (a % j == 0) {
return false;
}
}
return true;
}
}
配图说明: