Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, November 3, 2020

Java Program To Find LCM for Two Large Numbers

1.Overview

In this short article, you'll learn how to find the LCM for two large numbers. Here, we are going to use BigInteger class to hold the large values.

Example:

large value 1: 123456789123456789123456

large value 2: 987654321987654321987654

Output lcm : 20322105226083421931844602115480285409718968704

2. Example To Find LCM for Large Numbers

Let us use the two BigInteger object to hold the large values.

This BigInteger class has gcd() method which returns GCD for two numbers.

Next, use multiply() method to get the multiplication of two numbers.

Finally, use the formula LCM = large 1 * large 2 / gcd(large1 * large 2)

package com.javaprogramto.programs.maths;

import java.math.BigInteger;

public class LCMOfLargeNumbers {

	public static void main(String[] args) {
		
		BigInteger large1 = new BigInteger("123456789123456789123456");
		BigInteger large2 = new BigInteger("987654321987654321987654");

		BigInteger gcd = large1.gcd(large2);
		
		BigInteger multiply = large1.multiply(large2);
		
		BigInteger lcm = multiply.divide(gcd);
		
		System.out.println("Final LCM output: "+lcm.toString());
	
	}
}

Output:

Final LCM output: 20322105226083421931844602115480285409718968704

3. Conclusion

In this article, you've seen how to find the right lcm for bigger values using BigInteger class methods.

BigInteger API

GitHub Example

No comments:

Post a Comment

Please do not add any spam links in the comments section.