c - Making pascal's triangle with mpz_t's -


hey, i'm trying convert function wrote generate array of longs respresents pascal's triangles function returns array of mpz_t's. following code:

mpz_t* make_triangle(int rows, int* count) { //compute triangle size using 1 + 2 + 3 + ... n = n(n + 1) / 2 *count = (rows * (rows + 1)) / 2; mpz_t* triangle = malloc((*count) * sizeof(mpz_t));  //fill in first 2 rows mpz_t one; mpz_init(one); mpz_set_si(one, 1); triangle[0] = one; triangle[1] = one; triangle[2] = one;  int nums_to_fill = 1; int position = 3; int last_row_pos; int r, i; for(r = 3; r <= rows; r++) {     //left side     triangle[position] = one;     position++;      //inner numbers     mpz_t new_num;     mpz_init(new_num);     last_row_pos = ((r - 1) * (r - 2)) / 2;     for(i = 0; < nums_to_fill; i++) {         mpz_add(new_num, triangle[last_row_pos + i], triangle[last_row_pos + + 1]);         triangle[position] = new_num;         mpz_clear(new_num);         position++;     }     nums_to_fill++;      //right side     triangle[position] = one;     position++; }  return triangle; } 

i'm getting errors saying: incompatible types in assignment lines position in triangle being set (i.e.: triangle[position] = one;).

does know might doing wrong?

mpz_t define array of length 1 of struct __mpz_struct, prevents assignment. done because normal c assignment shallow copy , various gmp numeric types store pointers arrays of "limbs" need deep copied. need use mpz_set or mpz_init_set (or mpz_init_set_si) assign mp integers, making sure initialize destination before using former.

also, should call mpz_clear @ once every mpz_init (they're malloc , free in regard, , same reasons). calling mpz_init(new_nom) in outer loop mpz_clear(new_num) in inner loop, you're introducing bug evident when examine results of make_triangle. however, don't need new_num; initialize next element of triangle , use destination of mpz_add.

    mpz_init(triangle[position]);     mpz_add(triangle[position++], triangle[last_row_pos + i], triangle[last_row_pos + + 1]); 

small numeric optimization: can update last_row_pos using addition , subtraction rather 2 subtractions, multiplication , division. see if can figure out how.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -