0
点赞
收藏
分享

微信扫一扫

2.哥德巴赫猜想是任何不小于4的偶数,都可以写出两个质数之和的形式。它是世界三大数学难题之一,至今没有被完全证明。编写一个POSIX多线程程序验证100000000以内哥德巴赫猜想是对的。

陆佃 2022-03-13 阅读 114

java多线程实现:

class Source{
    private int num = 4;
    private boolean flag = true;
    private static int res[]=new int[100000001];
    private  static boolean True=false;
    public boolean get(){
        return Source.True;
    }
    public static void create(){
        res[0]=res[1]=1;
        for(int i=2;i<100000001;i++){
            if(res[i]==0){
                int cnt=2;
                while(cnt*i<100000001){
                    res[cnt*i]=1;
                    cnt++;
                }
            }
        }
    }
    public synchronized void add() throws Exception {
        if(this.flag == false) {
            super.wait();
        }
        Thread.sleep(50);
        this.num+=2;
        int i;
        for(i=num-1;i>=num/2;i-=2){
            if(Source.res[i]==0&&Source.res[this.num-i]==0){
//                System.out.println("当前执行线程:"+Thread.currentThread().getName()+" i = "+i+" j = "+(this.num-i)+"当前num = "+this.num);
                break;
            }
        }
        if(i<num/2){
            Source.True=true;
        }
        this.flag = true;
        super.notifyAll();
    }
}

class AddThreads implements Runnable{
    private Source source;
    public AddThreads(Source source) {
        this.source = source;
        Source.create();
    }
    @Override
    public void run() {
        for(int x=0;x<24999999;x++) {//100000000/4
            try {
                this.source.add();
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
     if(source.get()){
            System.out.println("猜想错误");
        }else{
            System.out.println("猜想正确");
        }
}

public class Multipro {
    public static void main(String[] args) {
        Source source = new Source();
        AddThreads at = new AddThreads(source);
        new Thread(at, "A").start();
        new Thread(at, "B").start();
        new Thread(at, "C").start();
        new Thread(at, "D").start();
    }
}

如果正确应该得到四个猜想正确:因为每个线程都只是执行一部分。
考虑到时间:这里只执行了一部分
在这里插入图片描述

举报

相关推荐

0 条评论