最大素数之和

时间:2019-05-24 11:49:57

标签: c sum primes

首先,我需要对在input.txt文件中提供的数字进行质数分解,然后要计算从该文件到C中输出文件的最大质数之和。

FILE *b, *k;

int maxPrimeFactors(int n)
{
int sum = 0;
int num = n;
int i;

int maxPrime = -1;

while (n % 2 == 0) {
    maxPrime = 2;
    n /= 2;
}


for (int i = 3; i <= sqrt(n); i += 2) {
    while (n % i == 0) {
        maxPrime = i;
        n = n / i;
    }
}


if (n > 2)
    maxPrime = n;


 for(maxPrime=2; maxPrime<= n; maxPrime)
{
    sum += maxPrime;  
}
return maxPrime;
}
 main()
 {
int n;
int sum;
if((b= fopen("input.txt","r")) == NULL){
    printf("I can't open the file for reading!");
        return 1;
        }

if((k= fopen("output.txt","w")) ==NULL){
printf("I can't open the file for writing! ");
return 2;
}


while(b= fopen("input.txt","r"))
{

    fscanf(b, "%d", &n);
    maxPrimeFactors(n);
}

fprintf(k, " The sum of the largest prime factors: %d", 
maxPrimeFactors(n));

直到现在我有了这个,但是我的代码有问题。

input.txt: 50 20 86 40

output.txt应该是: 最大质数的总和是:58

0 个答案:

没有答案