Here's mine:
#include <stdio.h> #include <stdlib.h> long *pascal(int row) { long *ret = (row == 1 ? NULL : pascal(row - 1)); ret = realloc(ret, sizeof(long) * row); ret[row - 1] = 1; for (int i = row - 2; i > 0; i--) ret[i] += ret[i - 1]; return ret; } int main(int argc, char *argv[]) { int row = atoi(argv[1]); long *data = pascal(row); for (int i = 0; i < row; i++) printf("%ld ", data[i]); printf("\n"); free(data); return 0; }
I ran your code and it does run well. However fails for large cases such as pascal(200000).
You mentioned you worked for Google and Amazon, how can you modify the code to get an answer for pascal(200000)
1. use double to get approximately-correct answers 2. use an abitrary-precision library like GMP
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int row = atoi(argv[1]); long data[row]; for (int i = 0; i < row; i++) { data[i] = 1; for (int j = i - 1; j > 0; j--) data[j] += data[j - 1]; } for (int i = 0; i < row; i++) printf("%ld ", data[i]); printf("\n"); return 0; }
Here's mine: