首先,我需要对在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