\$\begingroup\$
\$\endgroup\$
4
Your mission, even if you don't accept it, is to input three numbers from STDIN or file:
5 0.5 6
What you must do is evaluate this:
(5a + 0.5b)^6
This basically means that the first two numbers are the coefficients of a and b and the third is the exponent in a binomial expansion.
Rules:
- The first two numbers are either integers or simple terminating fractions.
- The third number is a positive integer.
- Do not use any inbuilt binomial functions from libs. (thanks to comments)
- The shortest code wins!
Go on, do it.
asked May 16, 2013 at 17:35
Soham Chowdhury
1,6471 gold badge14 silver badges23 bronze badges
4 Answers 4
\$\begingroup\$
\$\endgroup\$
Mathematica 36
InputForm@Expand[(#1 a + #2 b )^#3] &
Usage
InputForm@Expand[(#1 a + #2 b )^#3] &[5, .5, 6]
Result:
15625*a^6 +9375.*a^5*b +2343.75*a^4*b^2 +312.5*a^3*b^3 +23.4375*a^2*b^4 + 0.9375*a*b^5 + 0.015625*b^6
answered May 17, 2013 at 13:41
Dr. belisarius
5,5771 gold badge20 silver badges39 bronze badges
\$\begingroup\$
\$\endgroup\$
F# 153 chars 156 bytes
let a,b,n=1.,2.,3
let rec C k=if k=0 then 1 else (n-k+1)*C(k-1)/k
List.iter(fun i->printf"%+ga^%ib^%i"(pown a (n-i)*pown b i*float(C i)) (n-i) i)[0..n]
\$\begingroup\$
\$\endgroup\$
Python 2, 144 bytes
a,b,n=input();f=lambda n:-~(n and~-n*f(~-n))
for k in range(-~n):print"+ "[0**k]+"%d*(%d*a^%d)*(%d*b^%d)"%(f(n)/f(k)/f(n-k),a**(n-k),n-k,b**k,k)
answered Nov 5, 2017 at 23:57
Jonathan Frech
7,5111 gold badge23 silver badges44 bronze badges
\$\begingroup\$
\$\endgroup\$
3
C (C99), 223 chars
#include <stdio.h>
#include <math.h>
int f(int n,int k){
return k==0?1:(n*f(n-1,k-1))/k;
}
int main(void){
float a,b;int n;
scanf("%f%f%d",&a,&b,&n);
for(int k=0;k<=n;k++)
printf("%d*(%fa)^%d*(%fb)^%d+",f(n,k),a,n-k,b,k);
puts("0");
}
Input:
1 1 2
Output:
1*(1.000000a)^2*(1.000000b)^0+2*(1.000000a)^1*(1.000000b)^1+1*(1.000000a)^0*(1.000000b)^2+0
-
\$\begingroup\$ Do you have check if
k==0? I think a simplekwould do the same. \$\endgroup\$Johannes Kuhn– Johannes Kuhn2013年05月16日 18:24:07 +00:00Commented May 16, 2013 at 18:24 -
\$\begingroup\$ My brief attempt at optimization: ideone.com/tUlfKs \$\endgroup\$Mr. Llama– Mr. Llama2013年05月16日 20:49:56 +00:00Commented May 16, 2013 at 20:49
-
\$\begingroup\$ @GigaWatt: Well, it wouldn't be C99 then. \$\endgroup\$md5– md52013年05月17日 16:44:52 +00:00Commented May 17, 2013 at 16:44
!at least in APL and J). Indeed, the winner of that question used J's!. It would certainly have been longer if he had to hand-code it, and assuming that this question does not allow their use. \$\endgroup\$