Least Common Multiple (LCM)


In arithmetic and number theory, the least common multiple (also known 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. For example, LCM(2,3) = 6 and LCM(6,10) = 30.

If a = 0 or b = 0, then return with LCM(a, b) = 0, else go to Step 2.
Calculate absolute values of the two numbers.
Initialize lcm as the higher of the two values computed in Step 2.
If lcm is divisible by both absolute values, then return.
Increment lcm by 1 and go to Step 4.

LCM.java (least common multiple)

 // Java program to find the LCM 
 class LCM {
   public static void main( String[ ] args ) {
     // Find LCM between two command-line arguments.
     int a   = Integer.parseInt( args[0] );
     int b   = Integer.parseInt( args[1] );
     int lcm = 0;

     // Step 1
     if ( ( a == 0 ) || ( b == 0 ) ) {
       System.out.printf( "The LCM of %d and %d is %d.", a, b, lcm );
       return;
     }

     // Step 2
     a = Math.abs( a );
     b = Math.abs( b );

     // Step 3
     // Maximum number between a and b is stored in lcm
     lcm = ( a  b ) ? a : b;

     // Always true
     while( true ) {
       // Step 4
       if ( ( lcm  a == 0 ) && ( lcm  b == 0 ) ) {
         System.out.printf( "The LCM of %d and %d is %d.", a, b, lcm );
         break;
       }
       // Step 5
       lcm++;
     }
   }
 }
shell> java LCM