Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cassert>
- #include <stdexcept>
- using namespace std;
- int Factorial(int n) {
- if (n < 0) {
- throw out_of_range("N is negative"s);
- }
- // крайний случай
- if (n <= 1) {
- return 1;
- }
- return Factorial(n - 1) * n;
- }
- int FactorialCycle(int n) {
- if (n < 0) {
- throw out_of_range("N is negative"s);
- }
- int result = 1;
- // крайний случай
- if (n <= 1) {
- return result;
- }
- for (int i = 2; i <= n; ++i) {
- result *= i;
- }
- return result;
- }
- void Test() {
- assert(Factorial(5) == 120);
- assert(Factorial(1) == 1);
- assert(Factorial(0) == 1);
- try {
- Factorial(-2);
- assert(false);
- } catch (const exception& except) {
- // мы этого и ждем, всё ок
- }
- }
- void TestCycle() {
- assert(FactorialCycle(5) == 120);
- assert(Factorial(1) == 1);
- assert(Factorial(0) == 1);
- try {
- FactorialCycle(-2);
- assert(false);
- }
- catch (const exception& except) {
- // мы этого и ждем, всё ок
- }
- }
- int main() {
- Test();
- TestCycle();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment