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: 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
cpp#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; }Recursive Approach
cpp#include <iostream> unsigned long long factorial(int n) { if (n < 0) { return -1; // Handle negative case } else if (n == 0 || n == 1) { return 1; // Base case } else { return n * factorial(n - 1); // Recursive case } } 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; }Notes:
- Assistant