C language daily practice
March 12, 2022
Article directory
Topic description
Xiaoming will sell a tank of goldfish in 5 times: the first time he sells half of all goldfish plus 1/2; the second time he sells the remaining one-third plus 1/3; the third time he sells the remaining goldfish A quarter plus 1/4; the fourth sale of the remaining fifth plus 1/5; the final sale of the remaining 11. Try programming to find out how many fish are in the original fish tank.
problem analysis
Assuming that the current number of goldfish is y
, the number of goldfish before the last fish sale is , and the number of x
fish sold is i
(starting from 1); according to the title, the following formula can be obtained:
which is
This is a polynomial, and the initial x
value needs to be found, so that when the formula is operated for the 4th time y=11
, in programming, we can use the exhaustive method to exhaustively enumerate the first x
value).
Code
#include <stdio.h>
int main()
{
int sum = 0; //总金鱼数
int i = 0;
int flag = 0;
double tmp = 0;
for(sum = 11; sum <= 1000; sum++) //穷举范围11~1000
{
tmp = (double)sum;
for(i = 1; i <= 4; i++)
{
tmp = tmp - (tmp + 1) / (i + 1);
}
if(tmp < 11.000001 && tmp > 10.999999) //最后剩下11条(浮点数判断需要考虑精度问题)
{
flag = 1; //找到匹配的结果
break;
}
}
if(flag)
printf("金鱼总数为%d\n", sum);
else
printf("error\n");
return 0;
}
operation result
online reference
Original link: http://c.biancheng.net/cpp/html/3317.html
Original part of the idea (optimization part)
#include<stdio.h>
int main()
{
int i, j, x, flag=0; /*flag作为控制标志*/
/*从23开始试探,步长为2*/
for( i=23; flag==0; i+=2 )
{
for( j=1,x=i; j<=4&&x>=11; j++ )
if( (x+1) % (j+1) == 0) /*判断x+1是否能整除j+1*/
x -= (x+1) / (j+1);
else
{
x=0;
break;
}
if(j==5 && x==11)
{
printf("原来鱼缸中共有%d条金鱼。\n", i);
flag = 1; /*求出结果,flag置1,退出试探*/
}
}
return 0;
}