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();
}
}