Java用不同方法计算1000以内素数和

package com.bailiban.test1;

import java.util.Scanner;

/**
 * 求100以内的质数
 */
public class PrimeNumber {
    public static void test1() {
        System.out.println("--------------------开始--------------------------------");
        int number = 0;
        int sum = 0;
        int innerNumber = 0;
        int count = 0; //100内有多少个质数
        for (number = 2; number <= 1000; number++) {
            for (innerNumber = 2; innerNumber <= number; innerNumber++) {
                if (number % innerNumber == 0 && number != innerNumber) {
                    break;
                }
                if (number % innerNumber == 0 && number == innerNumber) {
                    count++;
                    System.out.println("第" + count + "个质数=" + number);
                    sum = sum + number;
                }
            }
        }
        System.out.println("----------100以内总共有" + count + "个质数! 总和为:" + sum + "----------");
        System.out.println("--------------------结束--------------------------------");
    }

    public static void test2() {
        System.out.println("--------------------开始--------------------------------");
        int count1 = 0, count2 = 0;
        for (int i = 2; i <= 20; i++) {
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j != 0) {
                    count1++;
                }
            }
            int num = (int) Math.sqrt(i);
            if (count1 == (num - 1)) {
                System.out.println("素数:" + i);
                count2++;
            }
            count1 = 0;
        }
        System.out.println(count2);
        System.out.println("--------------------结束--------------------------------");
    }

    public static void test3() {
        System.out.println("--------------------开始--------------------------------");
        Scanner in = new Scanner(System.in);
        int x;
        System.out.println(" 2到x的素数范围,请输入x:");// 加入一个提示语句
        x = in.nextInt();
        System.out.println(" 2到" + x + "内的素数有:");
        int i, n;
        int sum = 0;
        for (i = 2; i <= x; i++) {
            for (n = 2; n <= (int) Math.sqrt(i); n++)
                if (i % n == 0)
                    break;
            if (n > (int) Math.sqrt(i))
                sum = sum + i;
            System.out.print(" " + i);
        }
        System.out.println();
        System.out.println("总和:" + sum);
        System.out.println("--------------------结束--------------------------------");
    }

    public static void test4() {

    }

    /**
     * 求1000以内的质数
     */
    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值