Skip to content
  • P
    Projects
  • G
    Groups
  • S
    Snippets
  • Help

dajavo / Programming2_HomeWork2

  • This project
    • Loading...
  • Sign in
Go to a project
  • Project
  • Repository
  • Issues 0
  • Merge Requests 0
  • Pipelines
  • Wiki
  • Snippets
  • Members
  • Activity
  • Graph
  • Charts
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
  • Files
  • Commits
  • Branches
  • Tags
  • Contributors
  • Graph
  • Compare
  • Charts
Switch branch/tag
  • Programming2_HomeWork2
  • recursive code
Find file
BlameHistoryPermalink
  • dajavo's avatar
    Add new file · 662f1b7c
    dajavo committed a month ago
    662f1b7c
recursive code 1.78 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#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");
}