vendredi 10 juin 2016

C++ defined long long but the output is limited


I am currently learning C++, so I am a beginner. I thought I'd make a small program to generate the Bessel polynomial terms. This is the program:

#include <iostream>

// x!
long long fact(const long long &x)
{
  long long z {1};
  for (long long i=1; i<=x; ++i)
    z *= i;
  return z;
}

// 2^n
long long pwr2(const int &n)
{
  long long z {1};
  for (long long i=0; i<n; ++i)
    z *= 2;
  return (n == 0 ? 1 : z);
}

// Bessel coefficients
long long bessel(long long *a, const long long &N)
{
  for (long long i=0; i<=N; ++i)
    a[i] = fact(N + i) / (pwr2(i) * fact(N - i) * fact(i));
  return *a;
}

int main()
{
  std::cout << "N = ";
  long long N;
  std::cin >> N;

  long long *a {new long long[N + 1]};
  *a = bessel(a, N);

  for (long long i=0; i<=N; ++i)
    std::cout << a[i] << ( i<N ? " " : "n");

  delete a;
  a = nullptr;

  return 0;
}

N=10 seems to be the limit. sizeof(long long) shows 8 (archlinux x64). fact(20) > (2^64)-1, so I'm stuck, even with long long. Is there a way to circumvent this limit?

The code, as you see it, is after I got desperate and modified all int to long long. I even added "ll" to all the numbers, there's no effect. I even removed the main parenthesis from the denominator and arranged the terms so that they divide, progressively, to somehow balance themselves, e.g.: fact(N+i)/fact(N-i)/fact(i)/pwr2(i), also no effect.


Aucun commentaire:

Enregistrer un commentaire