算法篇-ALGO-2 最大最小公倍数(贪心)

试题 算法训练 最大最小公倍数

锦囊
当n为奇数时,答案一定是n * (n-1) * (n-2)。

当n为偶数时,答案可能是(n-1) * (n-2) * (n-3),也可能是n * a * b,其中a>=n-3。

资源限制

时间限制:1.0s 内存限制:256.0MB

问题描述

已知一个正整数N,问从1~N中任选出三个数,他们的最小公倍数最大可以为多少。

输入格式

输入一个正整数N。

输出格式

输出一个整数,表示你找到的最小公倍数。

样例输入

9

样例输出

504

数据规模与约定

1 <= N <= 106。

思路: 当输入的n是一个奇数时,那么n、(n-1)、(n-2)这3个数任意两个数之间必定不含有公约数2。

当输入的n是一个偶数时,那么n和(n-2)必定含有公约数2,而(n-2)/2<=(n-3),且(n-3)是个奇数。

所以,当n%3!=0时,打印n*(n-1)*(n-3);

但是当n%3=0时,(n-3)%3也会等于0,而n/3<=(n-2);

所以,当n%3==0时,打印(n-1)(n-2)(n-3)。
题解:JAVA

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            int n = sc.nextInt();
            if (n < 3) {
                System.out.println(n);
                continue;
            }
            if (n % 2 != 0) {
                System.out.println((long) n * (n - 1) * (n - 2));
            } else {
                if (n % 3 != 0) {
                    System.out.println((long) n * (n - 1) * (n - 3));
                } else {
                    System.out.println((long) (n - 1) * (n - 2) * (n - 3));
                }
            }
        }
        sc.close();
    }
}

题解2:C++

#include<bits/stdc++.h>
#define ll long long//注意数据的范围
using namespace std;
int main()
{
	ll n,gcd;
	cin>>n;
	if(n<=2) cout<<n<<endl;
	else
	{
		if(n%2) cout<<n*(n-1)*(n-2)<<endl;
		else
		{
			if(n%3==0)
			{
				cout<<(n-1)*(n-2)*(n-3);
			}
			else
			{
				cout<<n*(n-1)*(n-3)<<endl;
			}
		}
	}
	return 0;
} 

题解3:C语言

#include<stdio.h>
#define ll long long//注意数据的范围
int main()
{
	ll n,gcd;
	scanf("%lld",&n);
	if(n<=2) printf("%lld\n",n);
	else
	{
		if(n%2) printf("%lld\n",n*(n-1)*(n-2));
		else
		{
			if(n%3==0)
			{
				printf("%lld\n",(n-1)*(n-2)*(n-3));
			}
			else
			{
				printf("%lld\n",n*(n-1)*(n-3));
			}
		}
	}
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值