Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Computing the factorial of an integer using factorial and iteration
//Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86 #include <iostream> long long rec_factorial(int num) { if (num == 0 || num == 1) { return 1; } else if (num < 0) { num = abs(num); // could still be written as num *=-1; return -1*(num*rec_factorial(num - 1)); } else { return num*rec_factorial(num - 1); } } // factorial without using recursion long long iter_factorial(int num) { long long fac{ 1}; if (num == 0 || num == 1) { return 1; } else if (num < 0) { num = abs(num); for (int i = 1; i <= num; i++) { fac *= i; } return -1*fac; } else { for (num; num >= 1; --num) { // fac *= num; } return fac; } } int main() { int num1{5}; int num2{-5}; std::cout << num1<< "! (using recursion) = " << rec_factorial(num1) << std::endl; std::cout << num1<< "! (using iteration) = " << iter_factorial(num1) << std::endl; std::cout << num2<< "! (using recursion) = " << rec_factorial(num2) << std::endl; std::cout << num2<< "! (using iteration) = " << iter_factorial(num2) << std::endl; return 0; }
run
|
edit
|
history
|
help
0
wcstombs_s wide string conversion with multibyte chars and locale + concatenation
VC++ windows exception
VC++ '-flag Fail
Visual Studio C++ wont accept >> or << past the initial declarations
ExtThes_Uniquify
Buggy Strcat
MSVC initializer code
Wide string to lowercase
OS_checker
VS'15 parameter pack sfinae