HDOJ 2098 分拆素数和

来源:互联网 发布:apache ab工具 编辑:程序博客网 时间:2024/05/20 08:42

HDACM2098
此题按常规方法去做会超时,所以就利用空间去换时间,用一个布尔数组的下标去表示数值,然后通过布尔值去判断该数是否为素数,在此之前,要先把布尔数组的下标为素数的布尔值为true即调用函数Prime(n)去求。

import java.util.Scanner;public class Main{    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        while (sc.hasNext()) {            int n =sc.nextInt();            if (n==0) {                break;            }            int count = 0;            boolean[] boo = Prime(n);            for (int i = 2; i < boo.length/2; i++) {                if (boo[i]&&boo[n-i]) {                    count++;                }            }            System.out.println(count);        }    }    public static boolean[] Prime(int m){        boolean[] boo = new boolean[m];        for (int i = 2; i < boo.length; i++) {            boo[i] = true;        }        for (int i = 2; i < boo.length; i++) {            if (boo[i]) {                for (int j = i*2; j < boo.length; j+=i) {                    boo[j]=false;                }            }        }        return boo;    }}
原创粉丝点击