Program to find the LCM & HCF of n numbers



class HcfLcm
{
    public static void main(String[] args)
    {
        int n,x;
        System.out.println("Number of integers: ");
         n = Integer.parseInt(System.console().readLine());
         if(n<1)
         {
             System.out.print("Invalid input!");
             System.exit(0);
         }
          int[] arr = new int[n];


          for(int i =0; i<n; i++)
          {
              System.out.print("Number "+(i+1)+":");
              x = Integer.parseInt(System.console().readLine());
              if(x==0)
              {
                   System.out.print("Invalid input: '0' not allowed");
                   System.exit(0);
              }
              else if(x<0)
              {
                   arr[i]=x*(-1);
              }
              else
              {
                   arr[i]=x;
              }
          }
          int arr3[] = new int[n];
        for(int i=0; i<n; i++)
        {
            arr3[i] = arr[i];
        }
        System.out.println("The LCM is: "+lcm(arr,n));
        int h = arr3[0];
        for(int i=1;i<n;i++)
        {
            h=hcf(arr3[i],h);
        }
        System.out.println("The HCF is: "+h);
    }   
    static int lcm(int arr[], int size)
    {
         int index,b1,b2,flag = 1;
        int arr2[]=new int[size];
        for(int i=0; i<size; i++)
        {
                arr2[i] = arr[i];
        }
       
        while(flag == 1)
        {
              flag = index = 0;
              b1 = b2 = arr[0];
              for(int i=0 ; i<size; i++)
              {
                      if(b1 != arr[i])
                      {
                           flag = 1;
                      }
                      if(b2 > arr[i])
                      {
                           b2 = arr[i];
                           index = i;
                      }
              }
              if(flag==1)
              {
                    arr[index] = arr[index] + arr2[index];
              }
        }
        return arr[0];
    }

    static int hcf(int a,int b)
    {
        if(a==0)
        {
            return b;
        }
        return (hcf(b%a,a)); 
    }
}



OUTPUT:

Comments

  1. Nice article for find hcf for two number .one more way to find hfc and lcm visit HCF and LCM of two number

    ReplyDelete
  2. Nice article for find hcf for two number .one more way to find hfc and lcm visit HCF and LCM of two number

    ReplyDelete
  3. Program To Find The Lcm And Hcf Of N Numbers >>>>> Download Now

    >>>>> Download Full

    Program To Find The Lcm And Hcf Of N Numbers >>>>> Download LINK

    >>>>> Download Now

    Program To Find The Lcm And Hcf Of N Numbers >>>>> Download Full

    >>>>> Download LINK D8

    ReplyDelete

Post a Comment

Popular posts from this blog

HOW TO SETUP CODE BLOCKS FOR GRAPHICS PROGRAMS

Smile emoji using graphics in Java using Applet