验证哥德巴赫猜想

package december;

import java.util.Scanner;

/*
 * 哥德巴赫猜想:任何大于2的的偶数,都可以表示为两个素数之和。
 * 素数:大于1的自然数中,除一和自身外没办法被其他自然数整除的数
 * 要求验证:给出范围验证哥德巴赫猜想,
 * 思想:穷举法判断,只要有一个偶数不满足,它就是不成立的!
 */
public class Guss_5 {
	// 判断是否为素数
	public static boolean isPrime(int i) {
		boolean flag = true;
		if (i == 1)
			flag = false;
		for (int n = 2; n <= i - 1; n++) {
			if (i % n == 0) {
				flag = false;
				break;
			}
		}
		return flag;
	}

	// 近似验证哥德巴赫猜想
	public static boolean isGoldbach(int a) {
		boolean flag = false;
		//对于任何正偶数a都有 a = 1+(a-1), a = 2+(a-2)...  a = m/2 +m/2,两段都是一样的,只是前后相加顺序不同,所以i <= a/2次循环就够了
		for (int i = 1; i <= (a >> 1); i++) {
			if (isPrime(i) && isPrime(a - i)) {
				System.out.printf("%3d=%3d+%3d\t\t", a, i, (a - i));
				flag = true;
				break;
			}
		}
		return flag;
	}

	// 测试范围是否符合哥德巴赫猜想
	public static boolean test(int low, int height) {
		boolean flag = true;
		int j = 0;
		for (int i = low; i <= height; i++) {
			if (i % 2 == 0 && i > 2){
				if (isGoldbach(i)) {
					j++;
					if (j%5 == 0) {
						System.out.println();
					}
				} else {
					flag = false;
					break;
				}
			}
		}
		return flag;
	}

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入low:");
		int low = sc.nextInt();
		System.out.println("请输入height::");
		int height = sc.nextInt();
		System.out.println("下面开始测试"+low+"+"+height+"之间的数字:");
		if (test(low, height)) {
			System.out.println("哥德巴赫猜想成立!!");
		} else {
			System.out.println("哥德巴赫猜想不成立!");
		}
		sc.close();
	}
}

运行截图如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值