怎么用c语言Recamán's Sequence
Implement this in a program. Write two functions, one for solving it iteratively, one for solving it recursively.
Take two arguments from the command-line: an "i" or "r", and the term number (how many terms to print).
Print out which method executed (was selected) and all the terms (and the number of terms).
方案来自 梦想橡皮擦 狂飙组基于 GPT 编写的 “程秘”
只能依赖你的标题给你一个答案。
// Iterative function to solve Recamán's Sequence
void solveIteratively(int n) {
int i, a[n];
a[0] = 0;
printf("Iterative method selected\n");
printf("The first %d terms of Recamán's Sequence are:\n", n);
for (i = 1; i <= n; i++) {
int sub = a[i - 1] - i;
int j;
for (j = 0; j < i; j++) {
if (sub == a[j]) break;
}
if (j == i || sub < 0) {
a[i] = a[i - 1] + i;
} else {
a[i] = sub;
}
}
for (i = 0; i < n; i++) {
printf("%d\n", a[i]);
}
}
// Recursive function to solve Recamán's Sequence
int solveRecursively(int n, int a[], int index) {
if (index == 0) {
a[0] = 0;
return 1;
}
int sub = a[index - 1] - index;
int j;
for (j = 0; j < index; j++) {
if (sub == a[j]) break;
}
if (j == index || sub < 0) {
a[index] = a[index - 1] + index;
} else {
a[index] = sub;
}
return solveRecursively(n, a, index - 1);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s (i|r) number\n", argv[0]);
return 1;
}
int n = atoi(argv[2]);
if (n < 0) {
printf("Error: Invalid input\n");
return 1;
}
if (argv[1][0] == 'i') {
solveIteratively(n);
} else if (argv[1][0] == 'r') {
int a[n];
printf("Recursive method selected\n");
printf("The first %d terms of Recamán's Sequence are:\n", n);
solveRecursively(n, a, n - 1);
int i;
for (i = 0; i < n; i++) {
printf("%d\n", a[i]);
}
} else {
printf("Error: Invalid input\n");
return 1;
}
return 0;
}