Commit 7bf4032a by dajavo

Delete recursive code

parent 662f1b7c
Showing with 0 additions and 71 deletions
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MAX_LAYERS 15
double calculateA(int L, double X);
void calculateArrayRecursive(double X, double* A, double e, int L, int* numLayers);
void getInput(double* X, double* e);
void saveToFile(double* A, int numLayers);
int main() {
double X, e, A[MAX_LAYERS];
int numLayers = 0;
getInput(&X, &e);
calculateArrayRecursive(X, A, e, 1, &numLayers);
saveToFile(A, numLayers);
return 0;
}
void getInput(double* X, double* e) {
printf("Enter the value of X (|X| < 1): ");
scanf("%lf", X);
printf("Enter the value of e (0 < e < 1): ");
scanf("%lf", e);
if (fabs(*X) >= 1 || *e <= 0 || *e >= 1) {
printf("Invalid input! Ensure |X| < 1 and 0 < e < 1.\n");
exit(1);
}
}
double calculateA(int L, double X) {
double term = 1.0;
for (int i = 1; i < L; i++) {
term *= (2 * i - 1) / (double)(2 * i);
}
double A_L = pow(X, 2 * L - 1) * term / (2 * L - 1);
A_L *= pow(-1, L + 1);
return A_L;
}
void calculateArrayRecursive(double X, double* A, double e, int L, int* numLayers) {
if (L > MAX_LAYERS) return;
A[L - 1] = calculateA(L, X);
if (L > 1 && fabs(A[L - 1] - A[L - 2]) > e) {
printf("Stopping at L = %d because |A_L - A_{L-1}| > e\n", L);
return;
}
(*numLayers)++;
calculateArrayRecursive(X, A, e, L + 1, numLayers);
}
void saveToFile(double* A, int numLayers) {
FILE *f = fopen("F.txt", "w");
if (f == NULL) {
printf("Error opening file.\n");
exit(1);
}
fprintf(f, "Number of elements: %d\n", numLayers);
for (int i = 0; i < numLayers; i++) {
fprintf(f, "A%d = %.10lf\n", i + 1, A[i]);
}
fclose(f);
printf("Results saved to F.txt\n");
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment