求一个合数的最大质因子

【题目描述】
求一个合数的最大质因子。

【算法分析】
○ 一个合数 n 的非本身的最大因子为 n/2。
○ 判断素数的代码:
https://blog.csdn.net/hnjzsyjyj/article/details/119729401

#include <bits/stdc++.h>
using namespace std;
 
bool isPrime(int n) {
    if(n<2) return false;
    for(int i=2; i<=sqrt(n); i++) {
        if(n%i==0) return false;
    }
    return true;
}
 
int main() { //Find the primes between 2 and n
	int n;
	cin>>n;
	for(int i=2; i<=n; i++) {
		if(isPrime(i)) cout<<i<<" ";
	}
}
 
 
/*
in:
100
out:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
*/

○ 若 n 是合数,则在 1~sqrt(n) 范围内进行因子判别。简证如下:
给定一个数字 n,朴素的求其因子的方法为枚举 [1,n] 的所有数进行余数为 0 判定,算法时间复杂度为 O(n)。此处加入一个小优化,即若 m 为 n 的因子,那么 n/m 必然也为 n 的因子,不妨设 m≤n/m,则有 m≤sqrt(n),所以只需在 [1,sqrt(n)] 内枚举所有数进行余数为 0 判定即可,算法时间复杂度优化为 O(sqrt(n))。

【算法代码一】

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin>>n;

    int t;
    for(int i=2; i<=sqrt(n); i++) { //Prime Factorization
        while(n%i==0) {
            //cout<<i<<" ";
            n/=i;
        }
        t=i;
    }

    if(n>1) cout<<n;
    else cout<<t;

    return 0;
}

/*
in:462
out:11
*/


【算法代码二】

#include <bits/stdc++.h>
using namespace std;

void maxPrimeFactor(int n) {
    int ans=0;
    for(int i=n/2; i>1; i--) {
        if(n%i==0) {
            bool flag=true;
            for(int j=2; j*j<=i; j++) {
                if(i%j==0) {
                    flag=false;
                    break;
                }
            }
            if(flag && i>ans) ans=i;
        }
    }
    cout<<ans<<endl;
}

int main() {
    int n;
    cin>>n;

    maxPrimeFactor(n);

    return 0;
}


/*
in:180
out:5
*/



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/119729401
https://blog.csdn.net/hnjzsyjyj/article/details/138047200
https://blog.csdn.net/hnjzsyjyj/article/details/138084023
https://blog.csdn.net/joe_g12345/article/details/135307949
https://blog.csdn.net/hnjzsyjyj/article/details/138091319


 

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值