Seredenko-V

Untitled

Apr 26th, 2023
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <cassert>
  3. #include <stdexcept>
  4.  
  5. using namespace std;
  6.  
  7. int Factorial(int n) {
  8.     if (n < 0) {
  9.         throw out_of_range("N is negative"s);
  10.     }
  11.     // крайний случай
  12.     if (n <= 1) {
  13.         return 1;
  14.     }
  15.     return Factorial(n - 1) * n;
  16. }
  17.  
  18. int FactorialCycle(int n) {
  19.     if (n < 0) {
  20.         throw out_of_range("N is negative"s);
  21.     }
  22.  
  23.     int result = 1;
  24.     // крайний случай
  25.     if (n <= 1) {
  26.         return result;
  27.     }
  28.  
  29.     for (int i = 2; i <= n; ++i) {
  30.         result *= i;
  31.     }
  32.     return result;
  33. }
  34.  
  35. void Test() {
  36.     assert(Factorial(5) == 120);
  37.     assert(Factorial(1) == 1);
  38.     assert(Factorial(0) == 1);
  39.     try {
  40.         Factorial(-2);
  41.         assert(false);
  42.     } catch (const exception& except) {
  43.         // мы этого и ждем, всё ок
  44.     }
  45. }
  46.  
  47. void TestCycle() {
  48.     assert(FactorialCycle(5) == 120);
  49.     assert(Factorial(1) == 1);
  50.     assert(Factorial(0) == 1);
  51.     try {
  52.         FactorialCycle(-2);
  53.         assert(false);
  54.     }
  55.     catch (const exception& except) {
  56.         // мы этого и ждем, всё ок
  57.     }
  58. }
  59.  
  60. int main() {
  61.     Test();
  62.     TestCycle();
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment