The number of non-prime factors(预处理)

The number of non-prime factors(预处理)

In many programming competitions, we are asked to find (or count the number of) Prime Factors of an integer i. This is boring. This time, let’s count the number of Non-Prime Factors of an integer i, denoted as NPF(i).

For example, integer 100 has the following nine factors: {1,2–,4,5–,10,20,25,50,100}. The two which are underlined are prime factors of 100 and the rest are non-prime factors. Therefore, NPF(100) = 7.

Input
The first line contains an integer Q (1≤Q≤3⋅106) denoting the number of queries. Each of the next Q lines contains one integer i (2≤i≤2⋅106).

Output
For each query i, print the value of NPF(i).

Warning
The I/O files are large. Please use fast I/O methods.

题意:题目原意写的很清楚,求1到N非素数因子的个数,即,1-N中所有的质因子,但需要排除素数的情况。
代码分2个模块,一个是查找素数(getprm),一个是查找质因子( count)。
其中prm数组存放的是素数(本题没用,之前思路准备筛查剔除的),is数组代表的是当前点是否为素数(在后面查找质因子中使用)

include<cstdio>
include<cstring>
include<algorithm>
include<cmath>
include<iostream>
using namespace std;
const int maxn = 2000005;
bool is[maxn];
int prm[maxn];
int b[maxn];
void getprm(int n)
{
	int i, j, k = 0;
	int s, e = (int)(sqrt(0.0 + n) + 1);  //筛查素数只需要查到根号N即可
	memset(is, 1, sizeof(is));
	prm[k++] = 2;
	is[0] = is[1] = 0; //0和1不是素数,置0
	for (i = 4; i < n; i += 2) is[i] = 0;  //2的倍数全部置0
	for (i = 3; i < e; i += 2)  
		if (is[i])
		{
			prm[k++] = i;
			for (s = i * 2, j = i * i; j < n; j += s)  //质数的倍数全部置0
				is[j] = 0;
		}
	for (; i < n; i += 2)
		if (is[i])
			prm[k++] = i;
}
void count()
{
	for (int i = 1; i <= sqrt(2000000 + 0.5); i++)
	{
		int x = 2000000 / i;
		for (int j = i; j <= x; j++)
		{
			if (!is[i])
			{
				b[i * j]++;
			}
			if (!is[j] && i != j)
			{
				b[i * j]++;
			}
		}
	}
}
int main()
{
	int Q, n;
	scanf("%d", &Q);
	getprm(maxn);
	count();      //预处理打表
	while (Q--)
	{
		scanf("%d", &n);
		printf("%d\n",b[n]);
	}
}

本题也有一个很简便的方法,来自同学代码,可以观摩,值得学习!

#include<bits/stdc++.h>
using namespace std;
const int N=2000010;
int vis[N],a[N];
int main()
{
    for(int i=2;i<N;i++)
        if(vis[i]==0)
            for(int j=i+i;j<N;j+=i) vis[j]=1;
    for(int i=2;i<N;i++) if(vis[i]==1) for(int j=i;j<N;j+=i) a[j]++;
    int q,ii;
    scanf("%d",&q);
    while(q--)
    {
        scanf("%d",&ii);
        printf("%d\n",a[ii]+1);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值