Write a C# Sharp program to get the Least Common Multiple (LCM) of more than two numbers. Take the numbers from a given array of positive integers

  • برمجة سي شارب
  • برمجة

Write a C# Sharp program to get the Least Common Multiple (LCM) of more than two numbers. Take the numbers from a given array of positive integers. 
From Wikipedia,
In arithmetic and number theory, the least common multiple, lowest common multiple, or smallest common multiple of two integers a and b, usually denoted by lcm(a, b), is the smallest positive integer that is divisible by both a and b. Since division of integers by zero is undefined, this definition has meaning only if a and b are both different from zero. However, some authors define lcm(a,0) as 0 for all a, which is the result of taking the lcm to be the least upper bound in the lattice of divisibility.
Expected Output:
Original array elements:
4 6 8
LCM of the numbers of the said array of positive integers: 24
Original array elements:
1 2 3 4 5 6 7 8 9 10
LCM of the numbers of the said array of positive integers: 2520
Original array elements:
48 72 108
LCM of the numbers of the said array of positive integers: 432

الأجوبة

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums1 = { 4, 6, 8 };
            Console.WriteLine("Original array elements:");
            for (int i = 0; i < nums1.Length; i++)
            {
                Console.Write(nums1[i] + " ");
            }
            Console.WriteLine("\nLCM of the numbers of the said array of positive integers: " + test(nums1));
            int[] nums2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            Console.WriteLine("\nOriginal array elements:");
            for (int i = 0; i < nums2.Length; i++)
            {
                Console.Write(nums2[i] + " ");
            }
            Console.WriteLine("\nLCM of the numbers of the said array of positive integers: " + test(nums2));
            int[] nums3 = { 48, 72, 108 };
            Console.WriteLine("\nOriginal array elements:");
            for (int i = 0; i < nums3.Length; i++)
            {
                Console.Write(nums3[i] + " ");
            }
            Console.WriteLine("\nLCM of the numbers of the said array of positive integers: " + test(nums3));
        }
        static int gcd(int n1, int n2)
        {
            if (n2 == 0)
            {
                return n1;
            }
            else
            {
                return gcd(n2, n1 % n2);
            }
        }
        public static int test(int[] numbers)
        {
            return numbers.Aggregate((S, val) => S * val / gcd(S, val));
        }
    }
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...