我想把这个非递归函数转换成递归函数。我该怎么做呢?我必须找到可被7除的两个数字之间的数字数。
void count_divisors2(int min, int max) {
//Variable to store the counter
int counter = 0, i;
// Running a loop from A to B and check
// if a number is divisible by M.
for (i = min; i <= max; i++) {
if (i % 7 == 0)
counter++;
}
printf("%d", counter);
}发布于 2022-01-02 23:00:53
与其打印数字,不如返回计数:
非递归版本:
int count_divisors2(int min, int max) {
//Variable to store the counter
int counter = 0, i;
// Running a loop from A to B and check
// if a number is divisible by M.
for (i = min; i <= max; i++) {
if (i % 7 == 0)
counter++;
}
return counter;
}递归版本:
int count_divisors2(int min, int max) {
if (min > max)
return 0;
else
return (min % 7 == 0) + count_divisors2(min + 1, max);
}直接版本:
int count_divisors2(int min, int max) {
if (min <= max) {
if (min >= 0)
return (max / 7) - (min / 7) + (min % 7 == 0);
else
if (max >= 0)
return (max / 7) - (min / 7) + 1;
else
return (max / 7) - (min / 7) + (max % 7 == 0);
} else {
return 0;
}
}https://stackoverflow.com/questions/70560232
复制相似问题