Thursday, July 23, 2026

Newton's Binomial Theorem


I stumbled upon this formula in a book the other day and set about coding it in C from scratch. At the end of the day any summation can be easily turned into a for loop.

I also wrote my own functions for exponential, combinatorial numbers and factorial.

#include <stdio.h>

#define A 5
#define B 3
#define EXPN 7

int myexp(int base, int expn){
    int res=1; int i=0;
    if ((base == 0) && (expn == 0)) return 1;
      
    for (i=0;i<expn;i++){
      res=res*base;
    }
    return res;
}

int fact(int num){
  int i=0, res=num;
  
  if ((num == 0)) return 1;
  for (i=1; i<num;i++){
  res = res * (num-i);
  }
 return res;
}

int comb(int m, int n){
int res=0;
  if ((n == 0)) return 1;
  res=(fact(m) / (fact(n) * fact(m-n)));
  return res;
}

int binomial (int a, int b, int expn){
int k=0, res=0, combr=0;

  for (k=0;k<=expn;k++){
      combr = comb(expn,k);
      res = res + (combr * myexp(a,expn-k)*myexp(b,k));
  }
  return res;
}
void pretty(int expn){
    int i=0;

    for (i=0; i<expn; i++){
    printf("%d*a^%d * b^%d +\n",comb(expn,i),expn-i, i);
    }
    printf("%d*a^%d * b^%d\n",comb(expn,i),expn-i, i);
}
int main(){
   //printf("%d\n", comb(7,0));
   pretty(EXPN);
   printf("For a=%d and b=%d and exp=%d the result is...%d\n",A,B,EXPN, binomial(A,B,EXPN));
}

No comments:

Post a Comment