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

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;
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/loy_184548/article/details/49965339
文章标签: 26A
个人分类: codeforces ACM_暴力
上一篇codeforces-431C-k-Tree【dp】
下一篇codeforces-302A-Eugeny and Array
想对作者说点什么? 我来说一句

分解质因数与质因数乘积

2011年06月20日 512B 下载

没有更多推荐了,返回首页

关闭
关闭