Created
January 5, 2012 23:00
-
-
Save watmough/1567842 to your computer and use it in GitHub Desktop.
Display a line of Pascals 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
/* | |
* Pascals Triangle in C | |
* | |
* Hacker News: http://news.ycombinator.com/item?id=3428984 | |
* | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
long * next_line( long *line, int *length ) | |
{ | |
(*length)++; | |
long *next_line = (long*)malloc(sizeof(long)* *length); | |
int p=0; | |
for (; p<*length; ++p) { | |
if (p==0 || p==(*length)-1) { | |
next_line[p] = 1; | |
} else { | |
next_line[p] = line[p-1] + line[p]; | |
} | |
} | |
free(line); | |
return next_line; | |
} | |
int main( int argc, char **argv ) | |
{ | |
if (argc!=2) { | |
printf("Usage:\n\t%s <n>\nDisplay nth line of Pascal's triangle.\n",argv[0]); | |
exit(1); | |
} | |
long *line = NULL; | |
int length = 0; | |
int n = atoi(argv[1]); | |
int i=0; | |
for (; i<n; ++i) { | |
line = next_line( line,&length ); | |
} | |
for (i=0; i<length; ++i) { | |
printf ("%ld ",line[i]); | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment