w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Find the LCM and GCD of two numbers

Secondary Nav

C# Sharp Recursion : Exercise-12 with Solution

Write a program in C# Sharp to find the LCM and GCD of two numbers using recursion.
Test Data :
Input the first number : 10
Input the second number : 15
Expected Output
:
The GCD of 10 and 15 = 5
The LCM of 10 and 15 = 30

C# Sharp Code:

using System;
using System.Text;
 
   class RecExercise12
    {        
        public static void Main()
        {
            long num1, num2, hcf, lcm;
            Console.WriteLine("\n\n Recursion : Find the LCM and GCD of two numbers :");
		    Console.WriteLine("------------------------------------------------------");      
      
            Console.Write(" Input the first number : "); 
            num1 = Convert.ToInt64(Console.ReadLine());
            Console.Write(" Input the second number : "); 
            num2 = Convert.ToInt64(Console.ReadLine());
 
            hcf = gcd(num1, num2);
            lcm = (num1 * num2) / hcf;
 
            Console.WriteLine("\n The GCD of {0} and {1} = {2} ", num1, num2, hcf);
            Console.WriteLine(" The LCM of {0} and {1} = {2}\n", num1, num2, lcm);
            
 
        }
 
       static long gcd(long n1, long n2)
       {
           if (n2 == 0)
           {
               return n1;
           }
           else
           {
               return gcd(n2, n1 % n2);
           }
       }
 }

C# Sharp Practice online:


using System;
using System.Text;
 
   class RecExercise12
    {        
        public static void Main()
        {
            long num1, num2, hcf, lcm;
            Console.WriteLine("\n\n Recursion : Find the LCM and GCD of two numbers :");
		    Console.WriteLine("------------------------------------------------------");      
      
            Console.Write(" Input the first number : "); 
            num1 = Convert.ToInt64(Console.ReadLine());
            Console.Write(" Input the second number : "); 
            num2 = Convert.ToInt64(Console.ReadLine());
 
            hcf = gcd(num1, num2);
            lcm = (num1 * num2) / hcf;
 
            Console.WriteLine("\n The GCD of {0} and {1} = {2} ", num1, num2, hcf);
            Console.WriteLine(" The LCM of {0} and {1} = {2}\n", num1, num2, lcm);
            
 
        }
 
       static long gcd(long n1, long n2)
       {
           if (n2 == 0)
           {
               return n1;
           }
           else
           {
               return gcd(n2, n1 % n2);
           }
       }
 }

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program