关闭

codeforces-26A-Almost Prime【分解质因数】

标签: 26A
554人阅读 评论(0) 收藏 举报
分类:

codeforces-26A-Almost Prime【分解质因数】

                time limit per test2 seconds    memory limit per test256 megabytes

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.

input
10
output
2

input
21
output
8

题目链接:cf-26A

题目大意:问从1-n的数字中,存在几个数字,他的质因数有且只有两个,并且这两个质因数都是素数

题目思路:套用分解质因数模板即可

以下是代码:

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
/*============分解质因数===================
prime_factor()传入n, 返回不同质因数的个数
f存放质因数,nf存放对应质因数的个数
先调用initprime()。
=========================================*/

#define MAXN 200100
#define PSIZE 100000
int f[MAXN],nf[MAXN];
int plist[PSIZE], pcount=0;
bool isPrime[MAXN+1]; 
void initprime()  
{  
    memset(isPrime, true, sizeof(isPrime));
    int sq = sqrt((double)MAXN) + 1; 
    int i,j,k;  
    for(i = 2;i <= sq; i++)  
        if(isPrime[i])  
    for(j = 2,k = MAXN/i+1;j < k;j++)  
        isPrime[i*j] = false;  
    for( i = 2 ; i <= MAXN; i++)  
        if(isPrime[i])    
            plist[pcount++] = i;
    isPrime[0] = isPrime[1] = false;
}  

int prime_factor(int n) {
    int cnt = 0;
    int n2 = sqrt((double)n);
    for(int i = 0; n > 1 && plist[i] <= n2; ++i)
        if (n % plist[i] == 0) {            
            for (nf[cnt] = 0; n % plist[i] == 0; ++nf[cnt], n /= plist[i]);
            f[cnt++] = plist[i];
        }
    if (n > 1) nf[cnt] = 1, f[cnt++] = n;
    return cnt;
}

int main(){
    int n;
    cin >> n;
    initprime();
    int ans = 0;
    for (int i = 1; i <= n; i++)
    {
        int cnt = prime_factor(i);

        if (cnt == 2)
        {
            if(isPrime[f[0]] && isPrime[f[1]]) ans++;
        }
        memset(f,0,sizeof(f));
    }
    cout << ans << endl;

    return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:128570次
    • 积分:4497
    • 等级:
    • 排名:第6571名
    • 原创:328篇
    • 转载:7篇
    • 译文:0篇
    • 评论:23条
    关注博客
    博客专栏
    最新评论