Refactoring C to C++ for Bernoulli Number calculation -


rosettacode has article calculation of bernoulli numbers. unfortunately not provide example in c++, 1 in c (as of december 27, 2016).

i not familiar c, lot of recognizable. how program adapted c++?

#include <stdlib.h> #include <gmp.h>  #define mpq_for(buf, op, n)\     {\         size_t i;\         (i = 0; < (n); ++i)\             mpq_##op(buf[i]);\     } while (0)  void bernoulli(mpq_t rop, unsigned int n) {     unsigned int m, j;     mpq_t *a = malloc(sizeof(mpq_t) * (n + 1));     mpq_for(a, init, n + 1);      (m = 0; m <= n; ++m) {         mpq_set_ui(a[m], 1, m + 1);         (j = m; j > 0; --j) {             mpq_sub(a[j-1], a[j], a[j-1]);             mpq_set_ui(rop, j, 1);             mpq_mul(a[j-1], a[j-1], rop);         }     }      mpq_set(rop, a[0]);     mpq_for(a, clear, n + 1);     free(a); }  int main(void) {     mpq_t rop;     mpz_t n, d;     mpq_init(rop);     mpz_inits(n, d, null);      unsigned int i;     (i = 0; <= 60; ++i) {         bernoulli(rop, i);         if (mpq_cmp_ui(rop, 0, 1)) {             mpq_get_num(n, rop);             mpq_get_den(d, rop);             gmp_printf("b(%-2u) = %44zd / %zd\n", i, n, d);         }     }      mpz_clears(n, d, null);     mpq_clear(rop);     return 0; } 

thanks! general recommendations helpful!

it work on c++ without changing guess, anyway there few things change:

  • malloc new: mpg_t * = new mpg_t[n+1];

    or: mpq_t * = (mpq_t *) malloc(sizeof(mpq_t) * (n + 1));

  • null nullptr

  • most c libraries have been renamed (and deprecated) from: something.h csomething #include <stdlib.h> #include <cstdlib>

  • you write (included in cstdint header):

    for (uint32_t = 0; <= 60; ++i) { /* ... */ }

    instead of:

    unsigned int i;

    for (i = 0; <= 60; ++i) { /* ... */ }


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -