【codeforces26A】Almost Prime


A. Almost Prime
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive.
Input

Input contains one integer number n (1 ≤ n ≤ 3000).
Output

Output the amount of almost prime numbers between 1 and n, inclusive.
Sample test(s)
Input

10

Output

2

Input

21

Output

8

題意:輸出小於等於n的有且只有兩個質因數的個數。

解題思路:本來看數據3000,就想着純打表,後來看看,也還有蠻多,就老老實寫吧,先用prime數組存1-1500之間的素數,然後判斷小於等於n之間的滿足題意的個數。

code:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
using namespace std;
int prime[250];
int is_prime(int n)
{
    for(int i=2;i<=n/2;i++)
        if(n%i==0)
           return 0;
    return 1;
}
bool is_alpme(int i)
{
	bool flag=false;
	int pos=0,nbr=i;
	while(1)
	{
		if(prime[pos]>nbr)
            return false;
		if(flag==false && nbr%prime[pos]==0)
		{
			flag=true;
			while(nbr%prime[pos]==0)
                nbr=nbr/prime[pos];
		}
		else if(flag==true && nbr%prime[pos]==0)
		{
			nbr=nbr/prime[pos];
			while(nbr%prime[pos]==0)
                nbr=nbr/prime[pos];
			if(nbr==1)
                return true;
			else
                return false;
		}
		if(prime[pos]==1499)
            return false;
		pos++;
	}
}
int main()
{
    int cnt=0;
    int res=0;
    int n;
    for(int i=2;i<1500;i++)
        if(is_prime(i)){
            prime[res++]=i;
        }
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
	{
		if(is_alpme(i))
            cnt++;
	}
    printf("%d\n",cnt);
    return 0;
}



發佈了68 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章