題目:
判斷101-200之間有多少個素數(shù)彩届,并輸出所有素數(shù)伪冰。
程序分析:
判斷素數(shù)的方法:用一個數(shù)分別去除2到sqrt(這個數(shù)),如果能被整除樟蠕,則表明此數(shù)不是素數(shù)贮聂,反之是素數(shù)。
程序
package com.ljy.tencent;
/**
* 題目:判斷101-200之間有多少個素數(shù)坯墨,并輸出所有素數(shù)寂汇。
* 程序分析:判斷素數(shù)的方法:用一個數(shù)分別去除2到sqrt(這個數(shù)),
* 如果能被整除捣染,則表明此數(shù)不是素數(shù),反之是素數(shù)停巷。
* @author liaojianya
* 2016年9月29日
*/
public class JudgePrimesNumber
{
public static void main(String[] args)
{
boolean flag = true;
int count = 0;
System.out.println("在101-200之間的素數(shù)有:");
for(int i = 101; i <= 200; i++)
{
for(int j = 2; j <= Math.sqrt(i); j++)
{
//如果i能被2~sqrt(i)中的任何一個數(shù)整除耍攘,則跳出該循環(huán)
if(i%j == 0)
{
flag = false;
break;
}
else
{
flag = true;
}
}
if(flag)
{
count++;
System.out.print(i + ", ");
}
}
System.out.println();
System.out.println("在101和200之間一共有" + count + "個素數(shù)");
}
}
優(yōu)化代碼程序:
package com.ljy.tencent;
/**
* 題目:判斷101-200之間有多少個素數(shù)榕栏,并輸出所有素數(shù)。
* 程序分析:判斷素數(shù)的方法:用一個數(shù)分別去除2到sqrt(這個數(shù))蕾各,
* 如果能被整除扒磁,則表明此數(shù)不是素數(shù),反之是素數(shù)式曲。
* @author liaojianya
* 2016年9月29日
*/
public class JudgePrimesNumber
{ static int count = 0;
static boolean flag = true;
public static void main(String[] args)
{
System.out.println("在101-200之間的素數(shù)有:");
for(int i = 101; i <= 200; i++)
{
JudgeFrames(i);
}
System.out.println();
System.out.println("在101和200之間一共有" + count + "個素數(shù)");
}
public static int JudgeFrames(int i)
{
if( i == 1)
{
flag =false;
}
else
{
for (int j = 2; j <= Math.sqrt(i); j++)
{
// 如果i能被2~sqrt(i)中的任何一個數(shù)整除妨托,則跳出該循環(huán)
if (i % j == 0 || i == 0)
{
flag = false;
break;
}
else
{
flag = true;
}
}
}
//如果flag為true則表示i這個數(shù)不能被2~sqrt(i)中的數(shù)整除,則將prime個數(shù)count自增1
if(flag)
{
count++;
System.out.print(i + ", ");
//如果打印數(shù)目超過10個吝羞,則換行
if(count%10==0){
System.out.println();
}
}
return count;
}
}
結(jié)果輸出
在101-200之間的素數(shù)有:
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
在101和200之間一共有21個素數(shù)