Home >Java >JavaBase >How to calculate the least common multiple in java

How to calculate the least common multiple in java

王林
王林forward
2019-11-27 14:39:496006browse

How to calculate the least common multiple in java

Problem description:

Given a positive integer N, ask three numbers randomly selected from 1~N, what is the maximum least common multiple of them.

Input format:

Enter a positive integer N.

Output format:

Output an integer representing the least common multiple you found.

Sample input:

9

Sample output:

504

Data scale and convention:

1 <= N <= 106

Recommended online learning video tutorials: java course

Ideas:

First declare a few concepts:

The least common multiple of two non-zero adjacent natural numbers is their product; the least common multiple of two adjacent odd numbers is their product; the least common multiple of two adjacent even numbers (except 0) is their product half.

Now when it comes to the least common multiple of three numbers, there are two situations according to the parity of N:

1. When n is an odd number: n, n-1, n-2 Product

2. When n is an even number: n-1, n-2, n-3 are a set of maximum solutions. If the answer is greater than the current value, it can only be the product greater than these three numbers. Then only one of the numbers can be changed into n, and the three numbers must also be relatively prime. n, n-2, n-3 even and odd are obviously not mutually prime; n, n-1, n-3 are even and odd; n, n-1, n-2 even and odd are obviously not mutually prime.

Then the answer can only be n-1, n-2, n-3 or n, n-1, n-3. However, although n and n-3 are an odd number and an even number, they are not continuous and may not be relatively prime, such as the three numbers 5, 6, and 3.

n is an odd number: n, n-1, n-2

n is an even number: n is a multiple of 3 n-1, n-2, n-3

n is not a multiple of 3 n, n-1, n-3

Examples are as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        long N=input.nextLong();
        long temp=0;
        if(N<=2){
            System.out.println(N);
        }
        else if(N%2==0){
            temp=(N-1)*(N-2)*(N-3);
            if(N%3!=0){
                temp=Math.max(temp,N*(N-1)*(N-3));
            }
            System.out.println(temp);

        }

        else {
            System.out.println(N*(N-1)*(N-2));
        }
    }


}

Tips: Consider the case of N<3, and be careful to use long in this question.

Recommended java related article tutorials: Getting started with java development

The above is the detailed content of How to calculate the least common multiple in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete