最多约数问题

对于给定的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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值