Advertisement
tresonance

MATHEMATICS BINOMIAL FORMAULA

May 7th, 2020
1,872
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.78 KB | None | 0 0
  1. //******************************************************************************
  2. // MathsPhysic Code
  3. // Binomial formula
  4. //******************************************************************************
  5.  
  6. //today is maths and we will try to copute (a + b)^n  = binomial theorem (Newton)
  7. #include <stdio.h>
  8. //we will use recursion to calculta the Pascal Triangle coefficient
  9. int pascal(int n, int p){
  10.     if(p == 0 || n == p)
  11.         return 1;
  12.     return pascal( n -1, p - 1 )  + pascal(n - 1,  p  ); //we add triangle previous line coef (see pascal)
  13. }
  14. //n - 1 is previous line and p-1 the previous column of current n box
  15. // p is current box column
  16.  
  17. //now, let's compute Newton binomial using Pascal coefficient
  18. int  main(int argc, char **argv){ // i will use command line
  19.     if (argc == 1)
  20.         return (-1);          //Error
  21.                               //Usage example : ./a.out (a + b)^3
  22.     int n = argv[1][6] - '0'; //argv[1][6] equal 3 in this example (above), 7th character
  23.                               // argv[1][6] - '0' , i use ascii table to convert it to integer
  24.                               // '0' is 48 in ascii table so it convert to int
  25.     int k = n;
  26.    
  27.     printf("%s = " , argv[1]);
  28.     int operator = argv[1][2] != '-'; //check if it is (a-b)^n or (a + b)^n
  29.     for (int i = 0; i<= n; i++){//i will print in color , to save line , i will use ternary operator
  30.         printf("\x1B[31m%d", pascal( n , i )); //pascal coefficient to print
  31.         printf("\x1B[32ma^%d", k--); //decrement l in each step for new recursion
  32.         printf("\x1B[33mb^%d", i); //printf coefficient in color in natural way
  33.  
  34.         if(i < n) // i use ternary operator to save line : it only to check the sign +/-
  35.             operator || i&1 ? printf(" + ") : printf(" -");
  36.     }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement