English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Write a pseudo-code that prints the LCM (Least Common Multiple) of two
numbers.

2007-10-25 21:38:33 · 2 answers · asked by zilla_mafia 2 in Science & Mathematics Mathematics

2 answers

Here's actual java code. Numbers may be passed to the program via args, but for simplicity x and y are initialized in the body of the main method. Note the use of the modulus operator, %, which gives the remainder when the first number is divided by the second. Following is the main method calculating the LCM of 175 and 245 followed by the output:

public static void main( String[] args ) {
System.out.println("Hello Zilla");
int x = 175;
int y = 245;
for(int n = 1; n < 20000000; n++){
if((n * x) % y == 0){
System.out.println("The LCM of " + x + " and " + y + " is " + n*x);
break;
}
}
}//CLOSE MAIN

OUTPUT:
Hello Zilla
The LCM of 175 and 245 is 1225

2007-10-26 03:42:51 · answer #1 · answered by jsardi56 7 · 0 0

This isn't particularly efficient for large numbers, but for small numbers its easy enough to do

-given a,b integers
-let c = a*b
-for p prime from 2 to min(a,b)
if (p divides a) AND (p divides b) then let c = c / p
if p satisfies above, reuse the same p again to a higher power. If p^2 divides both, take another factor of p out of c. Increase power until it fails. Then increment p
-print c

this terminates when p reaches the smaller of the two numbers, since worst case scenario is that the smaller is a prime, and the larger is a multiple of the smaller.

2007-10-25 22:09:40 · answer #2 · answered by math_ninja 3 · 0 1

fedest.com, questions and answers