please help me to have a program that will compute for n! (n factorial) which is the product of all numbers from 1 to n.

Dani AI

Generated

asked for code to compute factorial; suggested loops or recursion and pointed to general resources. Below are practical, ready-to-run options and a few cautions so the result is correct and useful long after this thread.

Iterative with overflow check (safe for small n):

#include <iostream>
#include <limits>
#include <stdexcept>

unsigned long long factorial(unsigned int n) {
unsigned long long res = 1;
for (unsigned int i = 2; i <= n; ++i) {
if (res > std::numeric_limits<unsigned long long>::max() / i) {
throw std::overflow_error("unsigned long long overflow");
}
res *= i;
}
return res;
}

int main() {
unsigned int n;
if (!(std::cin >> n)) return 0;
try {
std::cout << factorial(n) << '\n';
} catch (const std::overflow_error&) {
std::cout << "Result too large for unsigned long long\n";
}
return 0;
}

Note: unsigned long long holds up to 20! (2432902008176640000). 21! (51090942171709440000) will overflow, so check before multiplying.

If exact results for large n are needed, use a big-integer type such as Boost.Multiprecision::cpp_int (header-only) and the same loop:

#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>

using boost::multiprecision::cpp_int;

cpp_int factorial_big(unsigned int n) {
cpp_int res = 1;
for (unsigned int i = 2; i <= n; ++i) res *= i;
return res;
}

int main() {
unsigned int n;
if (!(std::cin >> n)) return 0;
std::cout << factorial_big(n) << '\n';
return 0;
}

Additional tips: prefer iterative for large n to avoid stack limits. For repeated queries, precompute and cache results. For huge n where speed matters, use specialized libraries (GMP) or faster algorithms (divide-and-conquer/prime-swing). For an approximate value use the gamma function or Stirling approximation (floating point only).

Recommended Answers

All 2 Replies

please help me to have a program that will compute for n! (n factorial) which is the product of all numbers from 1 to n.

OK, but this is a secret between you and me: factorial cpp

Hint1 : use a for loop.
Hint2 : if your up to it, use recursion.
Hint3 : Google oggle it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.