C语言程序设计之穷举法求解鸡兔数量问题的解决方案

一、问题描述:
有一群鸡和一群兔,两种动物只数相同。两种动物的脚的总数都是三位数,且这两个三位数的六个数字分别是0,1,2,3,4,5。编程求鸡和兔的只数是多少?它们的脚数各是多少?

二、编码实现:

#include <stdio.h>
 
int main(void)
{
	/* num:鸡兔数量 */
	int num, result;
	
	for(num = 50; num < 250; num++)
	{
		result = 0;
		
		/* 处理鸡脚问题 */
		result |= (1 << (2 * num % 10));
		result |= (1 << (2 * num % 100 / 10));
		result |= (1 << (2 * num / 100));
		
		/* 处理兔脚问题 */
		result |= (1 << (4 * num % 10));
		result |= (1 << (4 * num % 100 / 10));
		result |= (1 << (4 * num / 100));	
		
		/* 打印符合要求的结果 */
		if(result == 0x3F)
		{
			printf("鸡数:%d\t脚数:%d\n", num, 2 * num);
			printf("兔数:%d\t脚数:%d\n", num, 4 * num);
		}
	}
	
	return 0;
}

三、运行结果:

[ycxie@localhost Workspace]$ gcc -o demo demo.c
[ycxie@localhost Workspace]$ ./demo
鸡数:76	脚数:152
兔数:76	脚数:304

Leave a Reply

Your email address will not be published. Required fields are marked *