HDOJ 5018 质因子

5 篇文章 0 订阅
2 篇文章 0 订阅
Alexandra and Prime Numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2396    Accepted Submission(s): 787


Problem Description
Alexandra has a little brother. He is new to programming. One day he is solving the following problem: Given an positive integer N, judge whether N is prime.
The problem above is quite easy, so Alexandra gave him a new task: Given a positive integer N, find the minimal positive integer M, such that N/M is prime. If such M doesn't exist, output 0.
Help him!


Input
There are multiple test cases (no more than 1,000). Each case contains only one positive integer N.
N≤1,000,000,000.
Number of cases with N>1,000,000 is no more than 100.


Output
For each case, output the requested M, or output 0 if no solution exists.


Sample Input
3
4
5
6


Sample Output
1
2
1
2


Source
BestCoder Round #19

题目意思:给定一个M,当M/N为质数时,N最小为什么。
转换思路就是M/N为最大质因子。那么N就为最小的。

质因子是数论中的一个概念。已255为例子,那么255的因子有1 、3、5、15、17、51、85、255。那么其中为质数的是1、3、5、17 所以,质因子即为1、3、5、17 。所以255的最大质因子为17。

数论中定义因子:假设整数a,b。有且唯一存在整数q使得a=bq,那么b和q都称为a的因子。那么如果在前面的条件下b为素数那么b就是质因子了。质因子中最大的即为最大质因子。

对于求一个数的质因子。我最开始觉得应该需要打质素表,然后再选。后来看别人的代码发现其实在筛选过程中已经不需要打表了。

#include<bits/stdc++.h>
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
ll a[100];
int main(){
    int n,i,num=0; 
    scanf("%d",&n);
    for (i=2;i*i<=n;i++) 
        {  
            if (n%i==0) a[num++]=i;  
            while(n%i==0) n=n/i; //假如i=2那么当i=4时候也已经被除去了。不需要考虑打表质数。
        }  
      if (n>1) a[num++]=n;  
        for (i=0;i<num;i++)  
          printf("%d ",a[i]);  
     printf("\n");  

    return 0;
}

然后就是求最大质因数了,就不需要存入。只需要利用max函数就可以了

#include<bits/stdc++.h>
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;

int main(){
    ll n,ans ;
    while(cin>>n){
        if (n==1){
            cout<<"0"<<endl;
            continue;
        }
        ans = 0;
        ll ch = n;
        for(ll i = 2 ; i*i <= n ; i++){
            if(n%i == 0){
                ans = max(ans,i); 
                while(n%i==0) n /= i;
            }
        }
        if(n>1){
            ans = max(ans,n);
        }
        ans = ch/ans;
        cout<< ans <<endl;
    } 
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值