Advertisement
damesova

Рекурсивно изчисляване на НОК

Nov 15th, 2022
1,039
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             int[] nums1 = { 4, 6, 8 };
  6.  
  7.             Console.WriteLine("Original array elements:");
  8.  
  9.             for (int i = 0; i < nums1.Length; i++)
  10.             {
  11.                 Console.Write(nums1[i] + " ");
  12.             }
  13.  
  14.             Console.WriteLine("\nLCM of the numbers of the said array of positive integers: " + test(nums1));
  15.  
  16.             int[] nums2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  17.             Console.WriteLine("\nOriginal array elements:");
  18.             for (int i = 0; i < nums2.Length; i++)
  19.             {
  20.                 Console.Write(nums2[i] + " ");
  21.             }
  22.  
  23.             Console.WriteLine("\nLCM of the numbers of the said array of positive integers: " + test(nums2));
  24.  
  25.             int[] nums3 = { 48, 72, 108 };
  26.             Console.WriteLine("\nOriginal array elements:");
  27.             for (int i = 0; i < nums3.Length; i++)
  28.             {
  29.                 Console.Write(nums3[i] + " ");
  30.             }
  31.  
  32.             Console.WriteLine("\nLCM of the numbers of the said array of positive integers: " + test(nums3));
  33.         }
  34.  
  35.         static int gcd(int n1, int n2)
  36.         {
  37.             if (n2 == 0)
  38.             {
  39.                 return n1;
  40.             }
  41.             else
  42.             {
  43.                 return gcd(n2, n1 % n2);
  44.             }
  45.         }
  46.  
  47.         public static int test(int[] numbers)
  48.         {
  49.             return numbers.Aggregate((S, val) => S * val / gcd(S, val));
  50.         }
  51.     }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement