如何找到在c 600851475143最大的主要因素? [英] How to find the largest prime factor of 600851475143 in C?

查看:171
本文介绍了如何找到在c 600851475143最大的主要因素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用code找到600851475143最大的主要因素如下给出。结果
然而,这code不返回任何输出,甚至没有错误或警告。

我到哪里去了?

code:

 #包括LT&;&stdio.h中GT;诠释的main()
{
  INT I,J,K,强积金;
  对于(i = 1; I< 600851475143;我++)
  {
    如果(600851475143%我== 0)
    {
      K = 0;
      为(J = 1; J< = I; J ++)
      {
        如果(我引用%j == 0)
        {
          ķ++;
        }
      }
      如果(K == 2)
      {
        MPF = I;
      }
    }
  }
  的printf(中600851475143 \\ n此最大的主要因素是:%LD \\ N,MPF);
  返回0;
}


解决方案

而不是从1到循环的600851475143,你应该从循环2至600851475143平方根:

 长长NUM = 600851475143;
我长= 2;
而(I< =开方(NUM))
{
    //的printf(%鲁\\ n,NUM);
    如果(NUM%我== 0)
    {
        而(NUM%我== 0)
        {
            NUM / = I;
        }
        如果(NUM == 1)
        {
            NUM = I;
            打破;
        }
    }
        其他
        {
            我++;
        }
}
的printf(%录,NUM);

I try to find the largest prime factor of 600851475143 with the code as given below.
However, this code does not return any output, not even errors or warnings.

Where do I go wrong?

Code:

    #include<stdio.h>

int main()
{
  int i,j,k,mpf;
  for (i=1;i<600851475143;i++)
  {
    if(600851475143%i==0)
    {
      k=0;
      for(j=1;j<=i;j++)
      {
        if(i%j==0)
        {
          k++;
        }
      }
      if(k==2)
      {
        mpf=i;
      }
    }
  }
  printf("\nThe largest prime factor of 600851475143 is: %ld\n",mpf);
  return 0;
}

解决方案

Instead of looping from 1 to 600851475143, you should loop from 2 to the square root of 600851475143:

long long num=600851475143;
long i=2;   
while(i<=sqrt(num))
{   
    //printf("%lu\n",num);
    if(num%i==0)
    {
        while(num%i==0)
        {
            num/=i;
        }           
        if(num==1)
        {
            num=i;
            break;
        }
    }
        else
        {
            i++;
        }
}
printf("%lu",num);

这篇关于如何找到在c 600851475143最大的主要因素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆