//判断101-200之间有多少个素数,并输出所有素数。
class Demo
{
private Demo(){}
private static Demo instance = null;
private int count = 0;
public static synchronized Demo getInstance()
{
if(instance == null)
instance = new Demo();
return instance;
}
public void judgeSuShu(int integer)
{
if (integer == 2)
{
printFunction(integer+"\tis Su Shu");
this.count++;
return;
}
if (integer & 0b0000_0001 == 0)
{
return;
}
int i = 3;
while ( i <= Math.sqrt(integer) )
{
if (integer %i == 0)
return;
else
i += 2;
}
count++;
printFunction(integer+"\tis Su Shu");
}
private void showError(int integer)
{
System.out.println("输入值:"+integer+"必须为大于或等于2的自然数!");
System.exit(0);
}
private void printFunction(Object obj)
{
System.out.println(obj.toString());
}
public int getCount()
{
return this.count;
}
}
class MainClass
{
public static void main(String[] args)
{
Demo d = Demo.getInstance();
for(int i = 101; i <= 200; i++)
{
d.judgeSuShu(i);
}
System.out.println("个数总计:"+d.getCount());
}
}
/*
1. 单例设计模式分懒汉式和饿汉式:
饿汉式操作步骤:
a】 私有化构造函数
b】 创建私有化静态对象
c】 创建返回私有化静态对象的公有函数
懒汉式操作步骤:
a】 私有化构造函数
b】 创建空的私有化静态对象
c】 创建返回私有化静态对象的公有同步函数,如果私有化静态对象为空则new。
2. 开发主要用饿汉式,面试主要用懒汉式(延迟加载)。
3. 素数即质数,只能被1和本身整除。2是最小的为偶数的素数,所以比2大的所有偶数一律可以排除素数。判断只需要从2到
开方根为止即可。
4. int i = Math.sqrt(integer);
*/