Eratosthenes筛法 素数筛

普通判断素数的方法:(Java)

//import java.util.Scanner;

public class Isprim {

	public static void main(String[] args) {
//		Scanner input = new Scanner(System.in);
//		int num = input.nextInt();
		for(int i=2; i <= 10000; i++){
			if( isPrime(i) )
			   System.out.println(i);
		}
//		input.close();
	}
	
	public static boolean isPrime(int n){
		for (int i = 2;i <= Math.sqrt(n);i++ ){
			if (n%i==0)
				return false;
		}
		return true;
	}

}

Eratosthenes筛法 合数分解为若干个质数的乘积,从小到大把质数的倍数都除掉,剩下的就是质数。

{ 这个让人想到了微软的一道智力题:

对一批编号为1~100 全部开关朝上(开)的灯进行以下操作:

凡是1 的倍数反方向拨一次开关,2 的倍数反方向又拨一次开关,3 的倍数反方向又拨一次开关.......
问最后为关熄状态的灯的编号

return 素数是关,其余是开

}

#include<iostream>
#include<cmath>
#include<time.h>

#define N 1000000

int Eratosthenes(int n);
int printResult(bool *ininitialize,int n);

bool initialize[N+1];

int main()
{
	int n=100000;
	//std::cin >> n;
	clock_t t1,t2;
	t1 = clock();
	Eratosthenes(n);
	t2 = clock();
	std::cout<<t2-t1<<std::endl;
	return 0;
}
int Eratosthenes(int n)
{
	initialize[2] = true;
	for (int i = 3; i<= N; i++)
		initialize[i] = (i%2==0 ? 0:1);
	for (int i = 3; i< (int) sqrt(n*1.0); i++)
	{
		if(initialize[i])
		{
			for(int j = i; i*j<= n; j+=2)
			{
				initialize[i*j]=false;
			}
		}
	}
	printResult(initialize,n);
	return 0;
}
int printResult(bool *initialize,int n)
{
	for (int i = 2; i<= n; i++)
	{
		if (initialize[i])
			std::cout<<i<<" ";
	}
	return 0;
}

Java:(学习Vector,就用它写的,肯定不是最优的)

<pre name="code" class="java">import java.util.*;

public class Eratosthenes {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int num = input.nextInt();
		Vector<Boolean> a = new Vector<Boolean>();
		a.add(false);
		a.add(false);
		a.add(true);
		for (int i = 3; i <= num; i++)
			a.add((i % 2 == 0 ? false : true));
		eratosthenes(num, a);
		input.close();
	}

	public static int eratosthenes(int n, Vector<Boolean> a) {
		for (int i = 3; i < (int) Math.sqrt(n * 1.0); i++) {
			if (a.elementAt(i)) {
				for (int j = i; i * j <= n; j += 2) 
					a.setElementAt(false, i * j);
			}
		}
		printResult(a, n);
		return 0;
	}

	public static void printResult(Vector<Boolean> a, int n) {
		for (int i = 2; i <= n; i++) {
			if (a.elementAt(i))
				System.out.print(i+" ");
		}
	}
}


 
 

最近学习Java,顺便把原来的Cpp代码改一下贴出来互相交流(从算法出发,未考虑程序的健壮性)。若有错误,请及时纠正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值