Skip to content

Instantly share code, notes, and snippets.

@gwang
Created August 18, 2015 07:19
Show Gist options
  • Save gwang/17638a686716e9ebc09c to your computer and use it in GitHub Desktop.
Save gwang/17638a686716e9ebc09c to your computer and use it in GitHub Desktop.
Expend (x+y)^n for a given n
#include <stdlib.h>
#include <stdio.h>
int combine(int n, int m)
{
int s1, s2, i;
s1=s2=1;
for (i = m+1; i<=n; i++) s1 *= i;
for (i = 1; i<=(n-m); i++) s2 *= i;
return (s1/s2);
}
int main(int argc, char **argv)
{
int n, i;
n = atoi(argv[1]);
printf("(x+y)^%d = ", n);
for (i=0; i<=n; i++)
{
int coeff = combine(n, i);
if (i != 0) printf(" + ");
printf("%d", coeff);
if (i != n) printf("*x^%d", (n-i));
if (i != 0) printf("*y^%d", i);
}
printf("\n");
return(0);
}
def combine(n, m)
s1 = (m+1..n).inject(1, :*)
s2 = (1..n-m).inject(1, :*)
s1/s2
end
def expand(n)
ret = []
(0..n).each do |i|
t1 = ( i == n ) ? '' : "*x^#{n-i}"
t2 = ( i == 0 ) ? '' : "*y^#{i}"
ret << "#{combine(n, i)}#{t1}#{t2}"
end
"(x+y)^#{n} = #{ret.join(' + ')}"
end
puts expand(ARGV[0].to_i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment