欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

歌德巴赫猜想_Java

程序员文章站 2024-01-31 20:39:16
...
import java.util.*;

public class Welcome {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("输入一个大于6的偶数: ");
        int num = in.nextInt();

        if (num > 6 && (num % 2 == 0)) {
            Guess g = new Guess(num);
            g.getValue();
        } else {
            System.out.println("不符合输入规范...");
        }
        in.close();
    }
}

class Guess {
    private int num;

    public Guess () {
        this(8);
    }

    public Guess (int num) {
        this.num = num;
    }

    private boolean isPrime(int i) {
        for (int j = 2; j < i - 1; j++) {
            if (i % j == 0) {
                return false;
            }
        }
        return true;
    }

    public void getValue() {
        for (int i = 4; i <= this.num; i = i + 2) {
            for (int a = 2; a <= i / 2; a++) {
                if (isPrime(a) && isPrime(i - a)) {
                    System.out.println((i + " = " + a + "+" + (i - a)));
                    break;
                }
            }
        }
    }

}

 

相关标签: Java