📜  前n个自然数的LCM

📅  最后修改于: 2021-04-23 07:24:31             🧑  作者: Mango

给定一个数字n,使得1 <= N <= 10 ^ 6,任务是查找前n个自然数的LCM。

例子:

Input : n = 5
Output : 60

Input : n = 6
Output : 60

Input : n = 7
Output : 420 

我们强烈建议您单击此处并进行实践,然后再继续解决方案。

我们在下面的文章中讨论了一个简单的解决方案。
最小的数字可被前n个数字整除
上述解决方案适用于单输入。但是,如果我们有多个输入,则最好使用Eratosthenes筛网存储所有主要因子。如我们所知,如果LCM(a,b)= X,那么a或b的任何素因也将是’X’的素因。

  1. 用1初始化lcm变量
  2. 生成小于10 ^ 6的所有素数,并使用Eratosthenes筛子存储在数组素数中。
  3. 找到小于给定数字并等于质数幂的最大数。
  4. 然后将此数字与lcm变量相乘。
  5. 重复步骤3和4,直到素数小于给定的数字。

插图:

For example, if n = 10 
8 will be the first number which is equal to 2^3
then 9 which is equal to 3^2
then 5 which is equal to 5^1
then 7 which is equal to 7^1
Finally, we multiply those numbers 8*9*5*7 = 2520

以下是上述想法的实现。

C++
// C++ program to find LCM of First N Natural Numbers.
#include 
#define MAX 100000
using namespace std;
 
// array to store all prime less than and equal to 10^6
vector primes;
 
// utility function for sieve of sieve of Eratosthenes
void sieve()
{
    bool isComposite[MAX] = { false };
    for (int i = 2; i * i <= MAX; i++)
    {
        if (isComposite[i] == false)
            for (int j = 2; j * i <= MAX; j++)
                isComposite[i * j] = true;
    }
 
    // Store all prime numbers in vector primes[]
    for (int i = 2; i <= MAX; i++)
        if (isComposite[i] == false)
            primes.push_back(i);
}
 
// Function to find LCM of first n Natural Numbers
long long LCM(int n)
{
    long long lcm = 1;
    for (int i = 0;
         i < primes.size() && primes[i] <= n;
         i++)
    {
        // Find the highest power of prime, primes[i]
        // that is less than or equal to n
        int pp = primes[i];
        while (pp * primes[i] <= n)
            pp = pp * primes[i];
 
        // multiply lcm with highest power of prime[i]
        lcm *= pp;
        lcm %= 1000000007;
    }
    return lcm;
}
 
// Driver code
int main()
{
    // build sieve
    sieve();
    int N = 7;
   
    // Function call
    cout << LCM(N);
    return 0;
}


Java
// Java program to find LCM of First N Natural Numbers.
import java.util.*;
 
class GFG
{
    static int MAX = 100000;
 
    // array to store all prime less than and equal to 10^6
    static ArrayList primes
        = new ArrayList();
    // utility function for sieve of sieve of Eratosthenes
    static void sieve()
    {
        boolean[] isComposite = new boolean[MAX + 1];
        for (int i = 2; i * i <= MAX; i++)
        {
            if (isComposite[i] == false)
                for (int j = 2; j * i <= MAX; j++)
                    isComposite[i * j] = true;
        }
 
        // Store all prime numbers in vector primes[]
        for (int i = 2; i <= MAX; i++)
            if (isComposite[i] == false)
                primes.add(i);
    }
 
    // Function to find LCM of first n Natural Numbers
    static long LCM(int n)
    {
        long lcm = 1;
        for (int i = 0;
             i < primes.size() && primes.get(i) <= n;
             i++)
        {
            // Find the highest power of prime, primes[i]
            // that is less than or equal to n
            int pp = primes.get(i);
            while (pp * primes.get(i) <= n)
                pp = pp * primes.get(i);
 
            // multiply lcm with highest power of prime[i]
            lcm *= pp;
            lcm %= 1000000007;
        }
        return lcm;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        sieve();
        int N = 7;
       
        // Function call
        System.out.println(LCM(N));
    }
}
// This code is contributed by mits


Python3
# Python3 program to find LCM of
# First N Natural Numbers.
MAX = 100000
 
# array to store all prime less
# than and equal to 10^6
primes = []
 
# utility function for
# sieve of Eratosthenes
 
 
def sieve():
 
    isComposite = [False]*(MAX+1)
    i = 2
    while (i * i <= MAX):
        if (isComposite[i] == False):
            j = 2
            while (j * i <= MAX):
                isComposite[i * j] = True
                j += 1
        i += 1
 
    # Store all prime numbers in
    # vector primes[]
    for i in range(2, MAX+1):
        if (isComposite[i] == False):
            primes.append(i)
 
# Function to find LCM of
# first n Natural Numbers
 
 
def LCM(n):
 
    lcm = 1
    i = 0
    while (i < len(primes) and primes[i] <= n):
        # Find the highest power of prime,
        # primes[i] that is less than or
        # equal to n
        pp = primes[i]
        while (pp * primes[i] <= n):
            pp = pp * primes[i]
 
        # multiply lcm with highest
        # power of prime[i]
        lcm *= pp
        lcm %= 1000000007
        i += 1
    return lcm
 
 
# Driver code
sieve()
N = 7
 
# Function call
print(LCM(N))
 
# This code is contributed by mits


C#
// C# program to find LCM of First N
// Natural Numbers.
using System.Collections;
using System;
 
class GFG {
    static int MAX = 100000;
 
    // array to store all prime less than
    // and equal to 10^6
    static ArrayList primes = new ArrayList();
 
    // utility function for sieve of
    // sieve of Eratosthenes
    static void sieve()
    {
        bool[] isComposite = new bool[MAX + 1];
        for (int i = 2; i * i <= MAX; i++)
        {
            if (isComposite[i] == false)
                for (int j = 2; j * i <= MAX; j++)
                    isComposite[i * j] = true;
        }
 
        // Store all prime numbers in vector primes[]
        for (int i = 2; i <= MAX; i++)
            if (isComposite[i] == false)
                primes.Add(i);
    }
 
    // Function to find LCM of first
    // n Natural Numbers
    static long LCM(int n)
    {
        long lcm = 1;
        for (int i = 0;
             i < primes.Count && (int)primes[i] <= n;
             i++)
        {
            // Find the highest power of prime, primes[i]
            // that is less than or equal to n
            int pp = (int)primes[i];
            while (pp * (int)primes[i] <= n)
                pp = pp * (int)primes[i];
 
            // multiply lcm with highest power of prime[i]
            lcm *= pp;
            lcm %= 1000000007;
        }
        return lcm;
    }
 
    // Driver code
    public static void Main()
    {
        sieve();
        int N = 7;
       
        // Function call
        Console.WriteLine(LCM(N));
    }
}
 
// This code is contributed by mits


PHP


C++
// C++ program to find LCM of First N Natural Numbers.
#include 
using namespace std;
 
// to calculate hcf
int hcf(int a, int b)
{
    if (b == 0)
        return a;
    return hcf(b, a % b);
}
 
 
int findlcm(int a,int b)
{
    if (b == 1)
       
        // lcm(a,b)=(a*b)/hcf(a,b)
        return a;
   
    // assign a=lcm of n,n-1
    a = (a * b) / hcf(a, b);
   
    // b=b-1
    b -= 1;
    return findlcm(a, b);
}
 
// Driver code
int main()
{
    int n = 7;
    if (n < 3)
        cout << n; // base case
    else
        
        // Function call
        // pass n,n-1 in function to find LCM of first n natural
        // number
        cout << findlcm(n, n - 1);
     
    return 0;
}
 
// contributed by ajaykr00kj


Java
// Java program to find LCM of First N Natural Numbers
public class Main
{
  // to calculate hcf
  static int hcf(int a, int b)
  {
    if (b == 0)
      return a;
    return hcf(b, a % b);
  }
 
 
  static int findlcm(int a,int b)
  {
    if (b == 1)
 
      // lcm(a,b)=(a*b)/hcf(a,b)
      return a;
 
    // assign a=lcm of n,n-1
    a = (a * b) / hcf(a, b);
 
    // b=b-1
    b -= 1;
    return findlcm(a, b);
  }
 
  // Driver code.
  public static void main(String[] args)
  {
    int n = 7;
    if (n < 3)
      System.out.print(n); // base case
    else
 
      // Function call
      // pass n,n-1 in function to find LCM of first n natural
      // number
      System.out.print(findlcm(n, n - 1));
  }
}
 
// This code is contributed by divyeshrabadiya07.


Python3
# Python3 program to find LCM
# of First N Natural Numbers.
 
# To calculate hcf
def hcf(a, b):
     
    if (b == 0):
        return a
         
    return hcf(b, a % b)
     
def findlcm(a, b):
     
    if (b == 1):
         
        # lcm(a,b)=(a*b)//hcf(a,b)
        return a
     
    # Assign a=lcm of n,n-1
    a = (a * b) // hcf(a, b)
     
    # b=b-1
    b -= 1
     
    return findlcm(a, b)
 
# Driver code
n = 7
 
if (n < 3):
    print(n)
else:
     
    # Function call
    # pass n,n-1 in function
    # to find LCM of first n
    # natural number
    print(findlcm(n, n - 1))
 
# This code is contributed by Shubham_Singh


C#
// C# program to find LCM of First N Natural Numbers.
using System;
class GFG {
 
  // to calculate hcf
  static int hcf(int a, int b)
  {
    if (b == 0)
      return a;
    return hcf(b, a % b);
  }
 
  static int findlcm(int a,int b)
  {
    if (b == 1)
 
      // lcm(a,b)=(a*b)/hcf(a,b)
      return a;
 
    // assign a=lcm of n,n-1
    a = (a * b) / hcf(a, b);
 
    // b=b-1
    b -= 1;
    return findlcm(a, b);
  }
 
  // Driver code
  static void Main() {
    int n = 7;
    if (n < 3)
      Console.Write(n); // base case
    else
 
      // Function call
      // pass n,n-1 in function to find LCM of first n natural
      // number
      Console.Write(findlcm(n, n - 1));
  }
}
 
// This code is contributed by divyesh072019.


Javascript


输出
420

另一种方法:

这个想法是,如果数字小于3,则返回数字。如果该数字大于2,则找到n,n-1的LCM

  • 假设x = LCM(n,n-1)
  • 再次x = LCM(x,n-2)
  • 再次x = LCM(x,n-3)…
  • 再次x = LCM(x,1)…

现在的结果是x。

为了找到LCM(a,b),我们使用函数hcf(a,b),该函数返回(a,b)的HCF

我们知道LCM(a,b)=(a * b)/ HCF(a,b)

插图:

For example, if n = 7 
function call lcm(7,6)
now lets say a=7 , b=6

Now , b!= 1 Hence 
a=lcm(7,6) = 42 and b=6-1=5

function call lcm(42,5)
a=lcm(42,5) = 210 and b=5-1=4

function call lcm(210,4)
a=lcm(210,4) = 420 and b=4-1=3

function call lcm(420,3)
a=lcm(420,3) = 420 and b=3-1=2

function call lcm(420,2)
a=lcm(420,2) = 420 and b=2-1=1

Now b=1
Hence return a=420

下面是上述方法的实现

C++

// C++ program to find LCM of First N Natural Numbers.
#include 
using namespace std;
 
// to calculate hcf
int hcf(int a, int b)
{
    if (b == 0)
        return a;
    return hcf(b, a % b);
}
 
 
int findlcm(int a,int b)
{
    if (b == 1)
       
        // lcm(a,b)=(a*b)/hcf(a,b)
        return a;
   
    // assign a=lcm of n,n-1
    a = (a * b) / hcf(a, b);
   
    // b=b-1
    b -= 1;
    return findlcm(a, b);
}
 
// Driver code
int main()
{
    int n = 7;
    if (n < 3)
        cout << n; // base case
    else
        
        // Function call
        // pass n,n-1 in function to find LCM of first n natural
        // number
        cout << findlcm(n, n - 1);
     
    return 0;
}
 
// contributed by ajaykr00kj

Java

// Java program to find LCM of First N Natural Numbers
public class Main
{
  // to calculate hcf
  static int hcf(int a, int b)
  {
    if (b == 0)
      return a;
    return hcf(b, a % b);
  }
 
 
  static int findlcm(int a,int b)
  {
    if (b == 1)
 
      // lcm(a,b)=(a*b)/hcf(a,b)
      return a;
 
    // assign a=lcm of n,n-1
    a = (a * b) / hcf(a, b);
 
    // b=b-1
    b -= 1;
    return findlcm(a, b);
  }
 
  // Driver code.
  public static void main(String[] args)
  {
    int n = 7;
    if (n < 3)
      System.out.print(n); // base case
    else
 
      // Function call
      // pass n,n-1 in function to find LCM of first n natural
      // number
      System.out.print(findlcm(n, n - 1));
  }
}
 
// This code is contributed by divyeshrabadiya07.

Python3

# Python3 program to find LCM
# of First N Natural Numbers.
 
# To calculate hcf
def hcf(a, b):
     
    if (b == 0):
        return a
         
    return hcf(b, a % b)
     
def findlcm(a, b):
     
    if (b == 1):
         
        # lcm(a,b)=(a*b)//hcf(a,b)
        return a
     
    # Assign a=lcm of n,n-1
    a = (a * b) // hcf(a, b)
     
    # b=b-1
    b -= 1
     
    return findlcm(a, b)
 
# Driver code
n = 7
 
if (n < 3):
    print(n)
else:
     
    # Function call
    # pass n,n-1 in function
    # to find LCM of first n
    # natural number
    print(findlcm(n, n - 1))
 
# This code is contributed by Shubham_Singh

C#

// C# program to find LCM of First N Natural Numbers.
using System;
class GFG {
 
  // to calculate hcf
  static int hcf(int a, int b)
  {
    if (b == 0)
      return a;
    return hcf(b, a % b);
  }
 
  static int findlcm(int a,int b)
  {
    if (b == 1)
 
      // lcm(a,b)=(a*b)/hcf(a,b)
      return a;
 
    // assign a=lcm of n,n-1
    a = (a * b) / hcf(a, b);
 
    // b=b-1
    b -= 1;
    return findlcm(a, b);
  }
 
  // Driver code
  static void Main() {
    int n = 7;
    if (n < 3)
      Console.Write(n); // base case
    else
 
      // Function call
      // pass n,n-1 in function to find LCM of first n natural
      // number
      Console.Write(findlcm(n, n - 1));
  }
}
 
// This code is contributed by divyesh072019.

Java脚本


输出
420

时间复杂度: O(nlog n)