what is the most efficient way to calculate the least common multiple of two integers

I just came up with this, it definitely leaves something to be desired

```
int n = 7, m = 4, n1=n, m1=m;
while (m1 != n1) {
if (m1 > n1)n1 += n;
else m1 += m;
}
System.out.println("lcm is " + m1);
```

Take successive multiples of the larger of the two numbers until the result is a multiple of the smaller.

this might work..

```
public int LCM(int x, int y)
{
int larger = x>y? x: y,
smaller = x>y? y: x,
candidate = larger ;
while (candidate % smaller != 0) candidate += larger ;
return candidate;
}
```

The least common multiple of a and b is the product divided by the greatest common divisor. I.e. lcm(a, b) = ab/gcd(a, b). So the question becomes how to find the gcd. The Euclidean algorithm is generally how the gcd is computed. The direct implementation of the classic algorithm is efficient, but there are variations that take advantage of binary arithmetic to do a little better. See Knuth TAOCP volume 2, Seminumerical Algorithms.

I think that the approach of "reduction by the greatest common divider" should be faster. Start by calculating the GCD (e.g. using Euclid's algorithm), then divide the product of the two numbers by the GCD.

**Remember The least common multiple is the least whole number that is a multiple of each of two or more numbers.**

If you ae trying to figure out the LCM of three integers, follow these steps:

```
**Find the LCM of 19, 21, and 42.**
```

Write the prime factorization for each number. 19 is a prime number. You do not need to factor 19.

21 = 3 × 7 42 = 2 × 3 × 7 19

Repeat each prime factor the greatest number of times it appears in any of the prime factorizations above.

2 × 3 × 7 × 19 = 798

The least common multiple of 21, 42, and 19 is 798.

First of all, you have to find the greatest common divisor

```
for(int = 1; i <= a && i <= b; i++) {
if (i % a == 0 && i % b == 0)
{
gcm = i;
}
}
```

After that, using the GCM you can easily find the least common multiple like this

```
lcm = a / gcm * b;
```

I don't know whether it is optimized or not, but probably the easiest one:

```
public void lcm(int a, int b)
{
if (a > b)
{
min = b;
max = a;
}
else
{
min = a;
max = b;
}
for (i = 1; i < max; i++)
{
if ((min*i)%max == 0)
{
res = min*i;
break;
}
}
Console.Write("{0}", res);
}
```

Similar Questions

I'm looking for the most efficient way to search a blob of text (± 1/2KB) for many regular expressions stored in an array. Example code: patterns = [/patternA/i,/patternB/i,/patternC/m,...,/patternN/i

I'm working with processing, and I was wondering what the best (most efficient) way of ordering an array was. I basically want to be able to write a function that could take an array with, say, the in

What is the most efficient way of writing a producer/consumer queue where one thread is the producer and the other is a consumer. In one paper, the author said that it requires one atomic operation to

what is the most efficient way of checking this: A is scheduled for 4 - 7; B is scheduled for 5 - 8; the schedule above overlaps. How do I check in Java if A and B overlaps or not in the following ex

I developing a Ip filter and was guessing how i could, using any type of esque data structure, develop a VERY efficient and fast BlackList filter. What i want to do is simple, every incoming/outcoming

What is the most efficient way to concatenate N arrays of objects in JavaScript? The arrays are mutable, and the result can be stored in one of the input arrays.

What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type? I was thinking something along the lines of the code below but it seems l

What is the most efficient way to continually add two numbers together? For instance, I have something like the following: totalFloat = totalFloat + someFloatVar There's gotta be a more efficient way

If I have some card images for a Javascript game, what is the most efficient way to display those images? Is it best to just create a new object with the same image URL? Should I preload all images th

I'm trying to determine what is the most efficient way to load videos into a on a user click using jQuery. To give more context behind this, I'll have about 30 clips on YouTube that are each between

I have an Android project (targeting Android 1.6 and up) which includes native code written in C/C++, accessed via NDK. I'm wondering what the most efficient way is to pass an array of bytes from Java

This object is what it is all about: public class Unit { private String label; NumberRow numberRow; Unit(String label){ this.label=label; numberRow = new NumberRow(); } .... } It contains a label nam

What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to contin

I was curious what the most efficient way to swap two elements in an array in Perl would be. Say I want to switch the elements with indexes of 3 and 5 respectively, what would be the fastest way to do

Is there a more efficient way to write this controller code? This handles a form that passes a name and description field and then saves it in my model. I'm wondering if there is a way to pass all of

I need to create a program that synchronizes it's own task objects to tasks in outlook. During the operation, tasks in outlook may be created/updated/deleted. The most straightforward way is to itera

What's the most efficient way to calculate the byte length of a character, taking the character encoding into account? The encoding would be only known during runtime. In UTF-8 for example the charact

Any efficient algorithm to achieve the following:- Raw data:- var arr = [ [one, two, three, four, five] , [one, two, three, six, seven] , [one, two, eight, four, ten] /*

Given a string of a valid CSS color value: #fff #ffffff white rgb(255, 255, 255) Need to get an array of numbers of the following format: [R, G, B] What is the most efficient way of doing this in Ja

I have a bunch of DataTables that need to be converted to object[,] arrays (not object[][] arrays). What's the most efficient way to do this in terms of performance? I know I can do this by building m

Using C# what is the most reliable way to calculate network bandwidth speed? I've found a few examples using NetworkInterface, Performance Counters, native Win32 code, etc. but they all provide differ

I've always just used SELECT COUNT(1) FROM X but perhaps this is not the most efficient. Any thoughts? Other options include SELECT COUNT(*) or perhaps getting the last inserted id if it is auto-inc

I'm looking for the most effecient way to resolve a given url to its final end point, following all 30x redirects and location headers. Basically, I have a bunch of URLs like http://foo.com that when

Given two files (in this case, largish CSV files), what's the most efficient way in Powershell to determine if their content differs?

What's the most efficient way to iterate through an entire table using Datamapper? If I do this, does Datamapper try to pull the entire result set into memory before performing the iteration? Assume,

What's the most efficient way to pull culture information out of a resx's filename using C#? The solution should also handle there not being culture info in the file name (ie form1.resx). In that case

I have multiple files of text that I need to read and combine into one file. The files are of varying size: 1 - 50 MB each. What's the most efficient way to combine these files without bumping into th

What is the most efficient way to get live updates from an online sevrer without DDOSing it or slowing down the client application? *I heard about long-polling once but I'm not sure if it's the best w

I have two columns in my SQLite Database, name and score. I need to display the out put of all table records by score descending from highest value. I have this working at the moment but due to score

I have a data source which will provide data regularly for N listeners. I can control access to the data using a ReaderWriterLock but what should be used to signal all listeners that they can simultan

I'm starting to run a few ads on a website, and I'm trying to decide the best way to track performance. Specifically, What's the most efficient way to count clicks? About the only way I can think of

I am looking for a way that is as efficient as the Keys property (of type KeyCollection) of a generic dictionary. Using a Linq select statement would work, but it would iterate over the whole collecti

What is the most efficient way to concatenate two positive integers in Mathematica 7? cc[123, 4567] >> 1234567 What about more than two? cc[123, 4, 567, 89] >> 123456789

I have a string that contains a series of random words separated by commas: worda,sample,wordb,another,extra,exampleb This list will always be different. What is the most efficient way to replace the

I was wondering if someone could help me find the most efficient way of pulling data from two tables which have a common ID. A simple example is that I have two tables; customers and messages which h

I have a few GBs worth of strings, and for every prefix I want to find 10 most common suffixes. Is there an efficient algorithm for that? An obvious solution would be: Store sorted list of <string

After updating all products with stock levels, what is the best way to set all configurable products to be in stock? By best way, I mean quickest with least load on server. EDIT: I forgot to say, how

I am trying to figure out a way to read lines of data from multiple text files stored on HDFS server, in Python. I need to parse each line and keep only part of the data, so I prefer not to save the f

I've been playing with a number of different ways for including header.php and footer.php files for a site I am building. What I'm not sure about is the most efficient place to reference the several .

Is there a way to compare two arrays and show what is common to both of them? array1 = [pig, dog, cat] array2 = [dog, cat, pig, horse] ???? What do I type to show that [pig, dog, c

I'm trying to index items inside an exchange mailbox so: What is the most efficient way to iterate through all the folders and items in an exchange mailbox using MAPI and/or Redemption Data Objects (R

What's the most efficient way to convert a Matrix{T} of size 1*N or N*1 in Julia to a Vector{T}? For example, say I have a = [1,3,5] b = a' Both a and b are of type Array{Int,2} (i.e. Matrix{Int}). W

my apologies if this is a duplicate, i couldn't find it anywhere.. say i've got a bunch of data frames, and i want to convert all of their column names to lowercase. what's the most efficient way to d

I've made a mod for Minecraft which allows Lua modding. Everything works fine, but normally the names of methods are obfuscated in MC. What's the best way to make the normal function names redirect to

I have two lists like x = ['a', 'b', 'c', 'd'] and y = [1, 2, 3, 4] I have to create a dict from these two lists so that result is { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } I do it using the following dic

I am looking for the most efficient way of converting image file to Base64 String in Android. The image has to be sent in a single Base64 String at once to backend. First I use imageToByteArray and th

What is the most efficient/elegant way to filter all paths by a base path? I have a path list and a base path, and I want a to get a list of paths that are children of the base path: public IList<s

What is the most efficient way (i.e., the fewest number of keystrokes) to edit the default Django settings file in Vim to use SQLite? The bare settings file looks like this: # Django settings for mysi

I am writing some application logic which can recognize malformed or malicious http post data requests made to an IIS 5 aspx page. What is the most efficient way to terminate a bad request? At the poi

All these do it, but what is the most efficient way? $(selector).html(''); $(selector).text(''); $(selector).children().remove();