Last active
October 14, 2015 03:07
-
-
Save fangdingjun/d9c1f518a512ad8c584a to your computer and use it in GitHub Desktop.
This code print a Pascal triangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
var N = 12 | |
for i := 0; i <= N; i++ { | |
for j := 0; j <= i; j++ { | |
if j == 0 { | |
for k := 0; k <= N-i; k++ { | |
fmt.Printf(" ") | |
} | |
} else { | |
fmt.Printf(" ") | |
} | |
fmt.Printf("%3d", combi1(i, j)) | |
} | |
fmt.Printf("\n") | |
} | |
} | |
/* | |
Pascal triangle formula | |
C(n,k) = n!/k!*(n-k)! | |
*/ | |
func combi1(n, k int) int { | |
switch k { | |
case 0: | |
return 1 | |
case 1: | |
return n | |
} | |
if n == k { | |
return 1 | |
} | |
l := n - k | |
if k > n { | |
l = k - n | |
} | |
return factorial(n) / (factorial(k) * factorial(l)) | |
} | |
func factorial(n int) int { | |
switch { | |
case n <= 0: | |
return 0 | |
case n <= 2: | |
return n | |
} | |
return n * factorial(n-1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment