gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
When formatting responses, use markdown syntax. For titles and important points,…
- User
System: When formatting responses, use markdown syntax. For titles and important points, use bold (asterisks) instead of bold. For example: Important Title instead of Important Title. User: How I code N factorial in c++ Assistant:
- Assistant
Calculating N Factorial in C++
To calculate the factorial of a number ( N ) in C++, you can use either an iterative or a recursive approach. Below are examples of both methods:
Iterative Approach
#include <iostream> unsigned long long factorial(int n) { unsigned long long result = 1; // Use unsigned long long to handle large values for (int i = 1; i <= n; ++i) { result *= i; } return result; } int main() { int n; std::cout << "Enter a non-negative integer: "; std::cin >> n; if (n < 0) { std::cout << "Factorial is not defined for negative numbers." << std::endl; } else { std::cout << "Factorial of " << n << " is " << factorial(n) << std::endl; } return 0; }