Java Goldbach's Conjecture

Hello everyone, I'm Ziph!

At first I do not know, I would like to do, this is the Goldbach conjecture it? Later, a Wikipedia learned that it is one of the world's three major modern mathematical problems. This is a more powerful Ha, instantly feeling the bald head! Few know how to feel good, but now you except to refuel the effort have no choice! Aha!
Here Insert Picture Description
Title :
Enter a even number greater than 6, the output of the even request which can be decomposed into two prime numbers and. Such as: 10 = 3 + 7 + 5 = 712

Requirements: Two groups of collaboration. A person responsible for an integer n and split into two integers, another person is responsible for writing a function, it determines a certain integer is a prime number.

Edition functions

//质数的校验
//普通的方法判断是否质数
//质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。
	public static boolean isPrime(int i) {
        for (int j = 2; j < i - 1; j++) {
            if (i % j == 0) {
                return false;
            }
        }
        return true;
    }

Optimized version function

//质数的校验
//开始我也只是一知半解,后来明白的所以也就写了下来,记录一下
//在哥德巴赫猜想中,一个数的因子是成对出现的,比如:100 = 2 * 50、100 = 4 * 25等
//所以,一个数a,它的的因子,一个肯定是<=根号下a的,另一个肯定是>=根号下a的
//因为我们两个数,一个是i,一个是j=a-i
//所以我们只要判断他们符合条件即可
public static boolean isPrime(int i){
		double m = Math.sqrt(i);
		for(int j = 3 ; j <= m ; j += 2){
			if (i % j == 0) {
				return false;
			}
		}
		return true;
	}

The full version of the code

import java.util.Scanner;

/** 
* @author Ziph
* @date 2020年2月26日
* @Email [email protected]
*/
public class Goldbach {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入一个大于6的偶数:");
		int a = sc.nextInt();
		
		//输入校验
		while (a < 6 || a % 2 != 0) {
			System.out.println("输入错误!");
			System.exit(0);
		}
		
		//将输入的值拆分成两个数,i代表第一个数,j代表第二个数
		for (int i = 3; i < a / 2; i += 2) {
			int j = a - i;
			//判断两个数均为质数
			if (isPrime(i) && isPrime(j)) {
				//打印输出结果
				System.out.println(a + " = " + i + " + " + j);
			}
		}
	}

	//质数的校验
	public static boolean isPrime(int i) {
        for (int j = 2; j < i - 1; j++) {
            if (i % j == 0) {
                return false;
            }
        }
        return true;
    }
}

Here Insert Picture Description

Published 67 original articles · won praise 118 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44170221/article/details/104515543