Find common multiples between element of array in C#?


Hi, how can I get the common multiples of all element of array for example I have this array 2 4 3 . And I want to get the common multiples I do this code but not working. Can someone help me please. Thanks.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {

 /*
  * Complete the getTotalX function below.
  */
 static int getTotalX(int[] a, int[] b) {
  /*
   * Write your code here.
   */
  int n = a.Length;
  for (int j = 0; j < n; j++) {
   // if we find the common multiples betwen element of array a we return those common mutiples
   if (a[i] * j == a[i + 1] * j && a[i] % j == 0 && a[i + 1] % j == 0) {
    return a[i] * j;
   }

  }

  static void Main(string[] args) {
   TextWriter tw = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

   string[] nm = Console.ReadLine().Split(' ');

   int n = Convert.ToInt32(nm[0]);

   int m = Convert.ToInt32(nm[1]);

   int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));

   int[] b = Array.ConvertAll(Console.ReadLine().Split(' '), bTemp => Convert.ToInt32(bTemp));
   int total = getTotalX(a, b);

   tw.WriteLine(total);

   tw.Flush();
   tw.Close();
  }
 }

Asked by:- LuneAgile
0
: 4693 At:- 6/29/2018 3:18:31 PM
C# Count common multiples







4 Answers
profileImage Answered by:- jaya

Here is all in one solution for you, which contains, GCD, LCM, common multiples functions in C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace CommonMultiples
{
    class Program
    {
        //get LCM of all elements of an array
        public static long LCMofArrayNumbers(int[] numbers)
        {
            long lcm = 1;
            int divisor = 2;
            while (true)
            {
                int cnt = 0;
                bool divisible = false;
                for (int i = 0; i < numbers.Length; i++)
                {
                    /**
                     * lcm (n1,n2,... 0)=0.For negative number we convert into
                     * positive and calculate lcm.
                     */
                    if (numbers[i] == 0)
                    {
                        return 0;
                    }
                    else if (numbers[i] < 0)
                    {
                        numbers[i] = numbers[i] * (-1);
                    }
                    if (numbers[i] == 1)
                    {
                        cnt++;
                    }
                    /**
                     * divide numbers by devisor if complete division i.e. without
                     * remainder then replace number with quotient; used for find
                     * next factor
                     */
                    if (numbers[i] % divisor == 0)
                    {
                        divisible = true;
                        numbers[i] = numbers[i] / divisor;
                    }
                }
                /**
                 * If divisor able to completely divide any number from array
                 * multiply with lcm and store into lcm and continue to same divisor
                 * for next factor finding. else increment divisor
                 */
                if (divisible)
                {
                    lcm = lcm * divisor;
                }
                else
                {
                    divisor++;
                }
                /**
                 * Check if all numbers is 1 indicate we found all factors and
                 * terminate while loop.
                 */
                if (cnt == numbers.Length)
                {
                    return lcm;
                }
            }
        }

       
        // Function to return gcd of a and b
        public static int gcd(int a, int b)
        {
            if (a == 0)
                return b;
            return gcd(b % a, a);
        }

        // Function to find gcd of 
        // array of numbers
        public static int findGCD(int[] arr, int n)
        {
            int result = arr[0];
            for (int i = 1; i < n; i++)
                result = gcd(arr[i], result);

            return result;
        }
        // method to calculate all
        // common divisors of two 
        // given numbers a, b --> 
        // input integer numbers
        public static int commDiv(int n)
        {

            // find gcd of a,b
           // int n = gcd(a, b);

            // Count divisors of n.
            int result = 0;
            for (int i = 1; i <= n; i++)
            {

                // if 'i' is factor of n
                if (n % i == 0)
                {
                    

                    // check if divisors are equal
                    if (n / i == i)
                    {
                        result += 1;
                        Console.WriteLine(i);
                    }
                    else
                    {
                        result += 2;
                        Console.WriteLine(i);
                    }
                }
            }

           
            return result;
        }

        //to get LCM of two numbers only
        public static int lcm2(int num1, int num2)
        {
            if (num1 == 0 || num2 == 0)
            {
                return 0;
            }
            else if (num1 < 0)
            {
                num1 = num1 * (-1);
            }
            else if (num2 < 0)
            {
                num2 = num2 * (-1);
            }
            int m = num1;
            int n = num2;
            while (num1 != num2)
            {
                if (num1 < num2)
                {
                    num1 = num1 + m;
                }
                else
                {
                    num2 = num2 + n;
                }
            }
            return num1;
        }


        public static List<int> GetCommonMultiples(int[] numbers)
        {
            var CommonList = new List<int>();
            var AllElementsLIst = new List<int>();
            int i,j = 0;

            //loop through all elements of array
            for( i = 0 ; i < numbers.Length; i++)
            {
                var Element = numbers[i];
                //save multiple of each elements of array multiple of upto 10 here
                for( j =1; j< 10; j++)
                {
                    AllElementsLIst.Add(j*Element);
                }
                
            }

            CommonList= AllElementsLIst.GroupBy(x => x).Where(g => g.Count() >= 2).Select(g => g.Key).ToList();

            Console.WriteLine("{0}", string.Join(", ", CommonList));


            return CommonList;
            
        }


        public static void Main()
        {
            int[] numbers = { 2, 22, 4 };
            
            Console.WriteLine("LCM(Least Common Multiple) of above numbers is");
            Console.WriteLine(LCMofArrayNumbers(numbers));


            Console.WriteLine("LCM of two numbers using repetative addition");
            Console.WriteLine(lcm2(2, 8));


            Console.WriteLine("Common divisible elements of array");
            int[] arr = { 2, 4, 8};
            int n = arr.Length;
            var CommonGCD=findGCD(arr, n);


            

            commDiv(CommonGCD);

            GetCommonMultiples(arr);

        }
    }
}

After executing above Program in C# console app, here is the output of the above program

lcm-gcd-common-multiples-in-csharp-min.png

Hope it helps.

2
At:- 7/1/2018 3:50:10 PM


profileImage Answered by:- jaya

I think you are trying to find least common multiples of all elements of an array, I tried executing your above code but it has lots of errors, so created my all program, which finds LCM of all elements of an array of LCM of two numbers in C#

using System;

namespace CommonMultiples
{
    class Program
    {
        //get LCM of all elements of an array
        public static long LCMofArrayNumbers(int[] numbers)
        {
            long lcm = 1;
            int divisor = 2;
            while (true)
            {
                int cnt = 0;
                bool divisible = false;
                for (int i = 0; i < numbers.Length; i++)
                {
                    /**
                     * lcm (n1,n2,... 0)=0.For negative number we convert into
                     * positive and calculate lcm.
                     */
                    if (numbers[i] == 0)
                    {
                        return 0;
                    }
                    else if (numbers[i] < 0)
                    {
                        numbers[i] = numbers[i] * (-1);
                    }
                    if (numbers[i] == 1)
                    {
                        cnt++;
                    }
                    /**
                     * divide numbers by devisor if complete division i.e. without
                     * remainder then replace number with quotient; used for find
                     * next factor
                     */
                    if (numbers[i] % divisor == 0)
                    {
                        divisible = true;
                        numbers[i] = numbers[i] / divisor;
                    }
                }
                /**
                 * If divisor able to completely divide any number from array
                 * multiply with lcm and store into lcm and continue to same divisor
                 * for next factor finding. else increment divisor
                 */
                if (divisible)
                {
                    lcm = lcm * divisor;
                }
                else
                {
                    divisor++;
                }
                /**
                 * Check if all numbers is 1 indicate we found all factors and
                 * terminate while loop.
                 */
                if (cnt == numbers.Length)
                {
                    return lcm;
                }
            }
        }

        //to get LCM of two numbers only
        public static int lcm2(int num1, int num2)
        {
            if (num1 == 0 || num2 == 0)
            {
                return 0;
            }
            else if (num1 < 0)
            {
                num1 = num1 * (-1);
            }
            else if (num2 < 0)
            {
                num2 = num2 * (-1);
            }
            int m = num1;
            int n = num2;
            while (num1 != num2)
            {
                if (num1 < num2)
                {
                    num1 = num1 + m;
                }
                else
                {
                    num2 = num2 + n;
                }
            }
            return num1;
        }

        public static void Main()
        {
            int[] numbers = { 2, 22, 4 };
            
            Console.WriteLine("LCM(Least Common Multiple) of above numbers is");
            Console.WriteLine(LCMofArrayNumbers(numbers));


            Console.WriteLine("LCM of two numbers using repetative addition");
            Console.WriteLine(lcm2(2, 8));

        }
    }
}

Executing it in Visual studio console app gives output as below

least-common-multiples-of-elements-using-csharp-min.png

There are two methods in the above program, one of which finds common multiples of array elements, I have commented out few important points to understand the code.

0
At:- 6/30/2018 8:38:02 AM


profileImage Answered by:- LuneAgile

Hi,thanks  Jaya for your reply. but just to explain you I need to return the common multiples for 2 and 4.

for exampple  we have this array 4,2 and the common multiples for 2 and 4 are 4,8,12,16

2*1=2

2*2=4

2*3=6

2*4=8

2*5=10

2*6=12

2*7=14

2*8=16

2*9=18

2*10=20

 

4*1=4

4*2=8

4*3=12

4*4=16

4*5=20

4*6=24

4*7=28

4*8=32

4*9=36

4*10=40

so the common multiples are the equal result product in this case 4 8 12 16 are the common multiples I  need to return those numbers and if I have in table more than 2 numbers need to return all common multiples between those numbers. Thanks.

0
At:- 6/30/2018 1:40:39 PM
Your question doesn't have proper details, you should have explained this while asking so it would have been easier, check my second answer, which contains GCD, LCM, and common multiples also 0
By : jaya - at :- 7/1/2018 3:43:36 PM


profileImage Answered by:- LuneAgile

Hi, Jaya Thanks so much.

0
At:- 7/1/2018 8:24:16 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use