JAVA算法:统计小于给定整数N的素数的个数

JAVA算法:统计小于给定整数N的素数的个数

问题描述

给你一个正整数n,统计小于n的素数的个数。

例如:当 n=10时,输出结果为4。

因为小于整数10的素数有2,3,5,7;一共4个素数。

问题分析

 

算法设计

package com.bean.algorithm.basic;

public class CountPrimesLessthanN {

	public static int countPrimes(int n) {
		if (n == 0 || n == 1)
			return 0;
		int[] primes = new int[n];
		int res = n - 2;
		// 1 => not prime
		// 0 => prime
		// initially all the elements are prime
		// marking 0 and 1 as non-prime
		primes[0] = 1;
		primes[1] = 1;
		for (int i = 2; i < n; i++) {
			// if the current element is prime
			if (primes[i] == 0) {
				for (int j = 2; i * j < n; j++) {
					// mark all the fators of current prime as non-prime
					if (primes[i * j] != 1) {
						primes[i * j] = 1;
						res--;
					}
				}
			}
		}
		return res;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//int N=10;
		int N=499979;
		int count=countPrimes(N);
		System.out.println("Count is: "+count);
	}
}

程序运行结果:

Count is: 4

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值