Advertisement
cska1312

N-th member of a number

Nov 5th, 2023
973
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. using System;
  2.  
  3. namespace N_th_member_of_a_number
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             Console.WriteLine("Please enter the number: ");
  10.             int a = int.Parse(Console.ReadLine());
  11.  
  12.             int iterativeProduct = iterativeVersion(a);
  13.  
  14.             static int iterativeVersion(int a)
  15.             {
  16.  
  17.                 int a1 = 2;
  18.                 int a2 = 4;
  19.                 int a3 = 6;
  20.                 int result = 0;
  21.  
  22.                 if (a == 1)
  23.                     return 2;
  24.                 if (a == 2)
  25.                     return 4;
  26.                 if (a == 3)
  27.                     return 6;
  28.  
  29.                 for (int i = 4; i <= a; i++)
  30.                 {
  31.                     result = 3 * a1 + 4 * a2 - 7 * a3;
  32.                     a1 = a2;
  33.                     a2 = a3;
  34.                     a3 = result;
  35.                 }
  36.                 return result;
  37.             }
  38.             Console.WriteLine($"Iterative result is: {iterativeProduct}");
  39.             Console.WriteLine();
  40.  
  41.             int recursiveProduct = recursiveVersion(a);
  42.  
  43.             static int recursiveVersion(int a)
  44.             {
  45.                 if (a == 1)
  46.                     return 2;
  47.                 if (a == 2)
  48.                     return 4;
  49.                 if (a == 3)
  50.                     return 6;
  51.  
  52.                 return 3 * recursiveVersion(a - 3) + 4 * recursiveVersion(a - 2) - 7 * recursiveVersion(a - 1);
  53.             }
  54.             Console.WriteLine($"Recursive result is: {recursiveProduct}");
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement