Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Pascal's triangle

Name: Anonymous 2012-01-05 17:41

Motivated by the Hacker News challenge in http://news.ycombinator.com/item?id=3429466 I just made this.


#include <stdio.h>
#include <stdlib.h>

int64_t* next_pascal_row(int64_t* previous_row, int64_t previous_size)
{
  int64_t* retval = (int64_t*)malloc(sizeof(int64_t)*(previous_size+2));
  int64_t i;
  for (i=0;i<previous_size+1;i++) {
    if (i==0 || i == previous_size) {
      retval[i] = 1;
    } else {
      retval[i] = previous_row[i-1] + previous_row[i];
    }
  }
  return retval;
}

void print_row(int64_t* row, int64_t size)
{
  int64_t i;
  for(i = 0; i < size; i++) {
    printf("%lld ",row[i]);
  }
  printf("\n");
}

int main()
{
  int64_t* first_row = (int64_t*)malloc(sizeof(int64_t));
  int64_t* previous_row;
  int64_t* next_row;
  int64_t i,size;
  first_row[0] = 1;
  size = 1;
  print_row(first_row,size);
  previous_row = first_row;
  for(i = 0; i<30;i++) {
    next_row = next_pascal_row(previous_row,size);
    size++;
    print_row(next_row,size);
    free(previous_row);
    previous_row = next_row;
  }
  free(next_row);
}

Opinions? Yeah, int64_t is probably a GNU extension, I don't care as long as it works with gcc. U mad? Also, post you're own solutions. If you can't do the Pascal, you can just go ahead and apply to your're nearest McDonald's, because you ain't worth shit.

Name: Anonymous 2012-01-06 0:12

>>42
Yes, that is because I use factorials. When fact(n) starts returning UINT64_MAX (18446744073709551615) or overflowing, the division in pascal() stops working properly. The SIGFPE happens when pascal() tries to divide by zero because of an overflow in either fact(col) or fact(row-col) which perchance happens to make either of them 0.
It shows up as early as row 20 because factorials grow faster than the binomial coefficients.

If one tried hard enough they could exploit the fact that n!/k! for k < n is the same as n*(n-1)*...*(k+1), to make it not overflow as quickly.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List