java50题----02素数

//判断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);
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值