实例三十三:循环检查满足条件的数
问题描述:
对于两个给定的素数 x 和 y ,求满足下列条件的最小自然数 N,即从 N 开始的每个自然数都能表示成 x 的倍数和 y 的倍数之和,即表示成 N = m1 * x + m2 * y ,其中m1,m2都为自然数。
For the two given prime numbers x and y, find the minimum natural number N that satisfies the following conditions, that is, each natural number starting from N can be expressed as the sum of multiples of x and multiples of y, that is, expressed as N = m1 * x + m2 * y , where m1 and m2 are both natural numbers.
算法分析:
- 首先让 x 和 y 的较小者为 k ,然后从 x + y 开始逐个检查每个自然数,看是否能表示 x 的倍数和 y 的倍数之和,一旦找到了 k 个连续自然数都符合这些条件,则这 k 个数的第一个数即为所求 N 的值。
First let the smaller of x and y be k, then check each natural number one by one starting from x + y to see if it can represent the sum of multiples of x and the multiple of y. Once k consecutive natural numbers are found, these conditions are met. , then the first number of these k numbers is the value of N sought.
#include<stdio.h>
int main(void)
{
int x,y,k,n;
int i,u=0,v=0;
printf("Please input the two prime numbers:");
scanf("%d%d",&x,&y);
n = x + y;
k = (x<y)?x:y;
i = 1;
while(i<=k)
{
u = 0;
do
{ u = u + x;
v = n - u;
if(v<y)
{ i=0;
break;
}
}while(v%y!=0);
n++;
i++;
}
printf("The minimum natural number that satisfies the condition is %d\n",n-k);
return 0;
}