程設作業(遞迴判斷兩個數互質)
阿新 • • 發佈:2019-02-19
giving an integer N (2 <= N <= 20) and a real number M (0.5 < M <= 1), output all proper fractions whose numerator is less than N ,and denominator is equal to or less than N, and value is equal to or less than M.
input: an integer N, a real number M in the type of double, in one line seperated by blank space.
output: proper fractions, each occupies a line. The proper fractions with smaller denominators are in the front. Between two different fractions with same denominator, the one whose numerator is smaller comes first. There is a ‘\n’ after the final fraction number.
Sample: input: 6 0.7 output: 1/2 1/3 2/3 1/4 1/5 2/5 3/5 1/6
答:
#include<stdio.h>
int IFhuzhi(int a, int b) { //a b互質當且僅當 b 與 a % b互質
if (a % b != 0)
return IFhuzhi(b, a % b);
else
if (b == 1)
return 1;
else
return 0;
}
int main(void) {
int N;
double M;
scanf("%d %lf", &N, &M);
int a, b;
for (b = 2; b <= N; ++b)
for (a = 1; a <= b; ++a)
if (a * 1.0 / b <= M && IFhuzhi(b, a) == 1)
printf("%d/%d\n", a, b);
return 0;
}