R语言学习——欧拉计划(3)Largest prime factor 求最大质因数

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

What is the largest prime factor of the number 600851475143 ?

翻译过后如下:

找出一个合数的最大质数因子

13195的质数因子有5,7,13和29.

600851475143的最大质数因子是多少?

f<-function(){
  s<-600851475143
  k<-sqrt(s)
  k<-as.integer(k)
  mm<-0
  for(i in 2:k)
  {
    while(s%%i==0)
    {
      s<-(s%/%i)
      if(mm<i)
      {
        (mm<-i)
      }
    }
  }
  print(mm)

}

暴力的C++代码:

#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
bool prime(long long x)
{
    if(x==2)
        return 1;
    for(long long i=2;i<=(long long)sqrt(( double)x);i++)
    {
        if(x%i==0)
            return 0;
    }
    return 1;
}
int main()
{
    long long s=600851475143;
    cout<<s<<endl;
    long long k=(long long)sqrt(( double)s);
    cout<<k<<endl;
    for(long long i=k;i>=1;i--)
    {
        if(prime(i)&&s%i==0)
        {
            cout<<i<<endl;
            break;
        }
    }
    return 0;
}
Answer:
6857

猜你喜欢

转载自www.cnblogs.com/caiyishuai/p/9720526.html