素数对

2018-03-12  本文已影响0人  sortinnauto

时间限制:1秒

空间限制:32768K

给定一个正整数,编写程序计算有多少对质数的和等于输入的这个正整数,并输出结果。输入值小于1000。
如,输入为10, 程序应该输出结果为2。(共有两对质数的和为10,分别为(5,5),(3,7))

输入描述:
输入包括一个整数n,(3 ≤ n < 1000)

输出描述:
输出对数

输入例子1:
10

输出例子1:
2

思路:

package Problems;


public class Sum {

    int count = 0;

    public boolean isZhiShu(int num) {
        boolean res = true;
        for (int i = 2; i <= num - 1; i++) {
            if (num % i == 0) {
                res = false;
            }
        }
        return res;
    }

    public int sum(int input) {
        if (number < 3 || number >= 1000) {
            return -1;
        }

        int start = 2;
        while (start <= number / 2) {    //检查一半即可
            if (isZhiShu(number - start) && isZhiShu(start)) {
                count++;
            }
            start++;
        }
    }
}

几个测试用例:

public class SumTest {

    Sum sum = new Sum();
    boolean result = false;
    int res = 0;

    @Before
    public void before() throws Exception {
    }

    @After
    public void after() throws Exception {
    }

    /**
     * Method: isZhiShu(int num)
     */
    @Test
    public void test_is_ZhiShu() throws Exception {
        result = sum.isZhiShu(23);
        assertEquals(true, result);

    }

    @Test
    public void test_input_10() throws Exception {
        res = sum.sum(10);
        assertEquals(2, res);

    }


    @Test
    public void test_input_30() throws Exception {
        res = sum.sum(30);
        assertEquals(3, res);

    }

    @Test
    public void test_input_100() throws Exception {
        res = sum.sum(100);
        assertEquals(6, res);

    }
}


上一篇下一篇

猜你喜欢

热点阅读