calgorithmmathseriesbinomial-theorem

Binomial distribution series in C Programming


I can write the pascal triangle with the code below. But my wish is to print the **

(a+b)^p

** series. My wish is as follows. Sample output:

(a+b)^p for unfolding p = 5
1
a^1 + b^1
a^2 + 2*a^1*b^1 + b^2
a^3 + 3*a^2*b^1 + 3*a^1*b^2 + b^3
a^4 + 4*a^3*b^1 + 6*a^2*b^2 + 4*a^1*b^3 + b^4
a^5 + 5*a^4*b^1 + 10*a^3*b^2 + 10*a^2*b^3 + 5*a^1*b^4 + b^5 

/******** MY Code *********/

 #include <stdio.h>
 long paskal(int,int);
 int main() 
 {
   int n=0;
   int m=0;
   int k=0;
   int s=0;
   printf("Enter number of rows:\n");
   scanf("%d", &n);
   for(k = 0; n >= k; k++) {
        for(m = 0; k >= m; m++) {
              long f = paskal(k, m);
                if(k==1)
                    printf("%ld",f);
                else
                    printf("a^%ld %ld b^%ld",k,f,k);
        }
        printf("\n");
    }
    return 0;
 }

 long paskal(int n, int i) {
    if(n == i || i == 0)
      return 1;
    else
      return paskal(n-1, i) + paskal(n-1, i-1);

   }

/********OUTPUT**********/

  Enter number of rows:                                                                                                   
  5 
  11                                                                                                                      
  a^2 1 b^2a^2 2 b^2a^2 1 b^2                                                                                             
  a^3 1 b^3a^3 3 b^3a^3 3 b^3a^3 1 b^3                                                                                    
  a^4 1 b^4a^4 4 b^4a^4 6 b^4a^4 4 b^4a^4 1 b^4                                                                           
  a^5 1 b^5a^5 5 b^5a^5 10 b^5a^5 10 b^5a^5 5 b^5a^5 1 b^5

I am sorry for my English. Thank You


Solution

  • In your desired output, I would suggest not printing the power of a when it is 1. So a^1 can just be a.

    Then here is how you could do it -- it is simple to remove the if that eliminates the ^1, if you still want it in the output

    // Helper function
    void factor(long f, char letter, int power) {
        if (f != 1)
            printf("*");
        if (power != 0) {
            printf("%c", letter);
            if (power != 1)
                printf("^%d", power);
        }
    }
    
    int main() {
        int n = 0;
        printf("Enter number of rows:\n");
        scanf("%d", &n);
        if (n > 0)
            printf("1\n");
        for (int k = 1; k < n; k++) {
            for (int m = 0; m <= k; m++) {
                if (m != 0)
                    printf(" + ");
                long f = paskal(k, m);
                if (f != 1)
                    printf("%ld", f);
                factor(f, 'a', k - m);
                factor(f, 'b', m);
            }
            printf("\n");
        }
        return 0;
    }