Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //******************************************************************************
- // MathsPhysic Code
- // Binomial formula
- //******************************************************************************
- //today is maths and we will try to copute (a + b)^n = binomial theorem (Newton)
- #include <stdio.h>
- //we will use recursion to calculta the Pascal Triangle coefficient
- int pascal(int n, int p){
- if(p == 0 || n == p)
- return 1;
- return pascal( n -1, p - 1 ) + pascal(n - 1, p ); //we add triangle previous line coef (see pascal)
- }
- //n - 1 is previous line and p-1 the previous column of current n box
- // p is current box column
- //now, let's compute Newton binomial using Pascal coefficient
- int main(int argc, char **argv){ // i will use command line
- if (argc == 1)
- return (-1); //Error
- //Usage example : ./a.out (a + b)^3
- int n = argv[1][6] - '0'; //argv[1][6] equal 3 in this example (above), 7th character
- // argv[1][6] - '0' , i use ascii table to convert it to integer
- // '0' is 48 in ascii table so it convert to int
- int k = n;
- printf("%s = " , argv[1]);
- int operator = argv[1][2] != '-'; //check if it is (a-b)^n or (a + b)^n
- for (int i = 0; i<= n; i++){//i will print in color , to save line , i will use ternary operator
- printf("\x1B[31m%d", pascal( n , i )); //pascal coefficient to print
- printf("\x1B[32ma^%d", k--); //decrement l in each step for new recursion
- printf("\x1B[33mb^%d", i); //printf coefficient in color in natural way
- if(i < n) // i use ternary operator to save line : it only to check the sign +/-
- operator || i&1 ? printf(" + ") : printf(" -");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement