Algebraic manipulation in C

144 Views Asked by At

Right now i'm looking to code a program that can do basic linear algebra from, Where i have 2 constants: A and B, where i can simply input their coefficients and add other values onto it.

Example:

Say i wanted to find the terms of the fibbonaci sequence

A
B

I want to take A + B and append it to file.

A
B
A+B

Now i want to add the 2nd and 3rd term

A
B
A + B
A + 2B

And so on.

I have a program that can do this for all numerical values just fine, however, i would like to see it go up algebraicly, Without using binets formula.

My only guess is to store the coefficents of A and B to 2 seperate files in order to calculate them and then print them out, however, If linear algebra is available in C it would be much easier.

Edit: Never mind, i forgot that this is a place for computer nerds, not math nerds

1

There are 1 best solutions below

0
nwellnhof On

Being a traditional imperative language, C has no built-in support for algebraic expressions. To compute the coefficients of your Fibonacci sequence, you can write a program like the following:

#include <stdio.h>

int main() {
    int i;
    int coeff_a_1 = 1;
    int coeff_b_1 = 0;
    int coeff_a_0 = 0;
    int coeff_b_0 = 1;

    printf("A\n");
    printf("B\n");

    for (i = 0; i < 15; i++) {
        int coeff_a = coeff_a_0 + coeff_a_1;
        int coeff_b = coeff_b_0 + coeff_b_1;

        printf("%dA + %dB\n", coeff_a, coeff_b);

        coeff_a_1 = coeff_a_0;
        coeff_b_1 = coeff_b_0;
        coeff_a_0 = coeff_a;
        coeff_b_0 = coeff_b;
    }

    return 0;
}

This will print:

A
B
1A + 1B
1A + 2B
2A + 3B
3A + 5B
5A + 8B
8A + 13B
13A + 21B
21A + 34B
34A + 55B
55A + 89B
89A + 144B
144A + 233B
233A + 377B
377A + 610B
610A + 987B

For more complex problems, I'd suggest to use a computer algebra system that offers C bindings.