HDU 2136 Largest prime factor 数论-素数

本文提供了一种巧妙的算法来解决HDOJ2136问题,即求给定数n的最大质因子的序号,通过筛选素数的方法进行打表,实现快速查询。

题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=2136

 

题意:

每个素数在素数表中都有一个序号,设1的序号为0,则2的序号为1,3的序号为2,5的序号为3,以此类推。现在要求输出所给定的数n的最大质因子的序号,0<n<1000000。

本题解法十分巧妙,利用筛选素数的方法进行打表,将某个素数和它的倍数所求的解都设置为该素数的序号,从小到大循环,这样数组中存放的就是输入的n对应的解了。

 

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;

/*
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
*/
#define N 1000000
int xh[N];

int main()
{
    int i,n,j;
    memset(xh,0,sizeof(xh));
    xh[1]=0;
    for(i=2,n=1;i<N;i++)
    {
        if(xh[i]==0)
        {
            for(j=i;j<N;j+=i)
                xh[j]=n;
            n++;
        }
    }
    while(scanf("%d",&n)!=EOF)
        printf("%d\n",xh[n]);
    return 520;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值