Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

gcd and lcm of an array

//We write the function to find the GCD of two numbers.

//We consider the first element of the array to be the gcd of itself and iterate through 
//each element of the array and update gcd with GCD of current element and previous gcd.

//We then find the LCM using the identity 
//           LCM*GCD = Multiplication of each number in the array
using System;
					
public class Program
{
	public static void Main()
	{
		string[] input = Console.ReadLine().Split(' ');
		int[] arr = Array.ConvertAll(input, int.Parse);
		int[] res = GCDandLCM(arr);
		Console.WriteLine("GCD is: {0}", res[0]);
		Console.WriteLine("LCM is: {0}", res[1]);
	}
	//GCD and LCM of numbers given in an array
	public static int[] GCDandLCM(int[] arr)
	{
		int gcd = arr[0];
		for(int i=1; i<arr.Length; i++)
		{
			gcd = GCD(gcd, arr[i]);
		}
		int lcm = Multiply(arr)/gcd;
		return new int[] {gcd, lcm};
	}
    //GCD using repetitive subtraction method
	public static int GCD(int a, int b)
	{
		while(a!=b)
		{
			if(a>b) a=a-b;
			else b=b-a;
		}
		return a;
	}
	public static int Multiply(int[] arr)
	{
		int mult = 1;
		for(int i=0; i<arr.Length; i++)
		{
			mult*=arr[i];
		}
		return mult;
	}
}
Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #gcd #lcm #array
ADD COMMENT
Topic
Name
3+7 =