Sunday 23 July 2017

Java Code to compute the smallest common multiple of two integers

Problem:

Design an algorithm to compute the smallest common multiple of two integers n and p. The SCM is defined as the smallest integer m such that n and p divide exactly into m.

Solution:

package com.myprograms;

import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class LeastCommonMultiple {

int firstNumber;
int secondNumber;
Set<Integer> firstNumberMultiples = new TreeSet<Integer>();
Set<Integer> secondNumberMultiples = new TreeSet<Integer>();
int result;

public static void main(String[] args) {
LeastCommonMultiple leastCommonMultiple = new LeastCommonMultiple();
leastCommonMultiple.getTheNumbers();
leastCommonMultiple.findFisrNumberMultiples();
leastCommonMultiple.findSecondNumberMultiples();
leastCommonMultiple.findLeastCommonMultiple();
leastCommonMultiple.printTheResult();
}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the first number");
firstNumber = scanner.nextInt();
System.out.println("enter the scond number");
secondNumber = scanner.nextInt();
scanner.close();
}

public void findFisrNumberMultiples(){
for(int i = 1; i <= 50; i++){
firstNumberMultiples.add(firstNumber * i);
}
}

public void findSecondNumberMultiples(){
for(int i = 1; i<= 50; i++){
secondNumberMultiples.add(secondNumber * i);
}
}

public void findLeastCommonMultiple(){
for(Integer i: firstNumberMultiples){
for(Integer j: secondNumberMultiples){
if(i == j){
result = i;
break;
}
}
if(result != 0){
break;
}
}
}

public void printTheResult(){
System.out.println(firstNumber + " multiples are " + firstNumberMultiples);
System.out.println(secondNumber + " multiples are " + secondNumberMultiples);
System.out.println("the Least common multiple of " + firstNumber + " and " + secondNumber + " is " + result);
}

}


Output:

enter the first number
5
enter the scond number
8
5 multiples are [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
8 multiples are [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, 144, 152, 160]
the Least common multiple of 5 and 8 is 40


enter the first number
4
enter the scond number
6
4 multiples are [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80]
6 multiples are [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120]
the Least common multiple of 4 and 6 is 12



No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...