给定一个数字n,找到可被1到n均等除的最小数字。
例子:
Input : n = 4
Output : 12
Explanation : 12 is the smallest numbers divisible
by all numbers from 1 to 4
Input : n = 10
Output : 2520
Input : n = 20
Output : 232792560
如果仔细观察, ans必须是数字1到n的LCM 。
要查找从1到n的数字的LCM –
- 初始化ans = 1。
- 迭代从i = 1到i = n的所有数字。
在第i次迭代中, ans = LCM(1,2,……..,i) 。这很容易做到,因为LCM(1,2,…。,i)= LCM(ans,i) 。
因此,在第i次迭代中,我们只需要做–
ans = LCM(ans, i)
= ans * i / gcd(ans, i) [Using the below property,
a*b = gcd(a,b) * lcm(a,b)]
注意:在C++代码中,答案很快超过了整数限制,甚至超过long long限制。
下面是逻辑的实现。
C++
// C++ program to find smallest number evenly divisible by
// all numbers 1 to n
#include
using namespace std;
// Function returns the lcm of first n numbers
long long lcm(long long n)
{
long long ans = 1;
for (long long i = 1; i <= n; i++)
ans = (ans * i)/(__gcd(ans, i));
return ans;
}
// Driver program to test the above function
int main()
{
long long n = 20;
cout << lcm(n);
return 0;
}
Java
// Java program to find the smallest number evenly divisible by
// all numbers 1 to n
class GFG{
static long gcd(long a, long b)
{
if(a%b != 0)
return gcd(b,a%b);
else
return b;
}
// Function returns the lcm of first n numbers
static long lcm(long n)
{
long ans = 1;
for (long i = 1; i <= n; i++)
ans = (ans * i)/(gcd(ans, i));
return ans;
}
// Driver program to test the above function
public static void main(String []args)
{
long n = 20;
System.out.println(lcm(n));
}
}
C#
// C# program to find smallest number
// evenly divisible by
// all numbers 1 to n
using System;
public class GFG{
static long gcd(long a, long b)
{
if(a%b != 0)
return gcd(b,a%b);
else
return b;
}
// Function returns the lcm of first n numbers
static long lcm(long n)
{
long ans = 1;
for (long i = 1; i <= n; i++)
ans = (ans * i)/(gcd(ans, i));
return ans;
}
// Driver program to test the above function
static public void Main (){
long n = 20;
Console.WriteLine(lcm(n));
}
//This code is contributed by akt_mit
}
Python3
# Python program to find the smallest number evenly
# divisible by all number 1 to n
import math
# Returns the lcm of first n numbers
def lcm(n):
ans = 1
for i in range(1, n + 1):
ans = int((ans * i)/math.gcd(ans, i))
return ans
# main
n = 20
print (lcm(n))
PHP
Javascript
输出 :
232792560