对于给定的2个随机正整数a<=b,计算a和b之间约数个数最多的数。设计一个算法求解最多约数问题。
输入:由文件名为input.txt的文本文件提供,第一行有两个正整数a和b
输出:若找到的a和b之间的约数个数最多的是x,将x的约数及其总数输出到output.txt
#include <stdio.h>
#include <stdlib.h>
void getMaxOfDivisorNumber(int minInteger, int maxInteger);
void main()
{
int integerMin;
int integerMax;
FILE* pReadFile = fopen( "E://input.txt", "r" );
if ( pReadFile == NULL ) {
printf("Open input file failed!\n");
return;
}
fscanf(pReadFile, "%d %d", &integerMin, &integerMax);
printf("%d, %d", integerMin, integerMax);
getMaxOfDivisorNumber(integerMin, integerMax);
fclose( pReadFile );
}
void getMaxOfDivisorNumber(int minInteger, int maxInteger)
{
int integer, countVar, i; //integer is between minInteger and maxInteger
int arraySize;
int *divisorNumArray;
int maxDivisorNumber;
FILE* pWriteFile = fopen("E://output.txt", "w");
if ( pWriteFile == NULL ) {
printf("Open output file failed!\n");
system("pause");
return;
}
// make sure that min integer is not larger than max integer
if (minInteger > maxInteger) {
//swap if minInteger > maxInteger
integer = minInteger;
minInteger = maxInteger;
maxInteger = integer;
}
arraySize = maxInteger - minInteger + 1;
divisorNumArray = (int*)malloc(arraySize*sizeof(int)); //dynamic memory allocation
//store divisor number of every integer into the dynamic array, namely divisorNumArray
for (integer = minInteger; integer <=maxInteger; integer++) {
for (i = 1, countVar = 0; i <= integer/2; i++) {
if (integer % i == 0)
countVar ++;
}
divisorNumArray[integer - minInteger] = countVar + 1;
}
//get max divisor number of the dynamic array and write it to output file
maxDivisorNumber = divisorNumArray[0];
for (i = 1; i < arraySize ; i++)
if (maxDivisorNumber < divisorNumArray[i])
maxDivisorNumber = divisorNumArray[i];
fprintf(pWriteFile, "Max of divisor number between %d and %d is: %d \n", minInteger, maxInteger, maxDivisorNumber);
//get all integers that have max divisor number and write it to output file
fprintf(pWriteFile, "Corresponding integers are:\n");
for (i = 0; i < arraySize; i++) {
if (divisorNumArray[i] == maxDivisorNumber)
fprintf(pWriteFile, "%d\n", i + minInteger);
}
free(divisorNumArray);
fclose(pWriteFile);
}