Project Euler Problem 3: Largest prime factor

Largest prime factor

Problem 3

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?


C++:

#include <iostream>

using namespace std;

long maxfact(long n)
{
    long ret=2L, i;

    while(n%2 == 0)
        n /= 2;

    for(i=3; i*i<=n; i+=2) {
        if(n%i == 0) {
            ret = i;
            n /= i;
            while(n%i == 0)
                n /= i;
        }
    }
    return (n==1)?ret:n;
}

int main()
{
    long n;

    while(cin >> n) {
        cout << maxfact(n) << endl;
    }

    return 0;
}


Run results:

13195     
29
600851475143
6857



参考链接:最大素因数


posted on 2017-03-18 07:45  海岛Blog  阅读(97)  评论(0编辑  收藏  举报

导航