Last active
December 23, 2015 23:09
-
-
Save obikag/6707692 to your computer and use it in GitHub Desktop.
Pascal's Triangle calculated using a recursive function in Lua.
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
--Recursive function to create the mathemeatical series | |
function pascal(col,row) | |
if(col == 0) or (col == row) then return 1 | |
else return pascal(col-1,row-1) + pascal(col,row-1) | |
end | |
end | |
--Prints Pascal's Triangle to the 'n'th row | |
function PascalTriangle(num) | |
if (num <= 0) then print("Number must be greater than zero") return end | |
for r = 0,num,1 do | |
for c = 0,r,1 do | |
io.write(pascal(c,r).." ") | |
end | |
print() | |
end | |
end | |
--Test Section | |
PascalTriangle(10) | |
--[[ | |
Output: | |
1 | |
1 1 | |
1 2 1 | |
1 3 3 1 | |
1 4 6 4 1 | |
1 5 10 10 5 1 | |
1 6 15 20 15 6 1 | |
1 7 21 35 35 21 7 1 | |
1 8 28 56 70 56 28 8 1 | |
1 9 36 84 126 126 84 36 9 1 | |
1 10 45 120 210 252 210 120 45 10 1 | |
]] | |
PascalTriangle(0) -- returns 'Number must be greater than zero' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment