📜  数的最小除数

📅  最后修改于: 2021-06-26 20:10:09             🧑  作者: Mango

给定数N,找到N的最小素数。

例子:

方法:

  • 检查数字是否可被2整除。
  • 从i = 3迭代到sqrt(N)并跳转2。
  • 如果任何数字除以N,则它是最小的素数除数。
  • 如果它们都不除,则N为答案。

下面是上述算法的实现:

C++
// C++ program to count the number of
// subarrays that having 1
#include 
using namespace std;
 
// Function to find the smallest divisor
int smallestDivisor(int n)
{
    // if divisible by 2
    if (n % 2 == 0)
        return 2;
 
    // iterate from 3 to sqrt(n)
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0)
            return i;
    }
 
    return n;
}
 
// Driver Code
int main()
{
    int n = 31;
    cout << smallestDivisor(n);
 
    return 0;
}


Java
// Java  program to count the number of
// subarrays that having 1
 
import java.io.*;
 
class GFG {
// Function to find the smallest divisor
static int smallestDivisor(int n)
{
    // if divisible by 2
    if (n % 2 == 0)
        return 2;
 
    // iterate from 3 to sqrt(n)
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0)
            return i;
    }
 
    return n;
}
 
// Driver Code
     
    public static void main (String[] args) {
     
        int n = 31;
        System.out.println (smallestDivisor(n));
         
    }
}


Python3
# Python3 program to count the number
# of subarrays that having 1
 
# Function to find the smallest divisor
def smallestDivisor(n):
 
    # if divisible by 2
    if (n % 2 == 0):
        return 2;
 
    # iterate from 3 to sqrt(n)
    i = 3;
    while(i * i <= n):
        if (n % i == 0):
            return i;
        i += 2;
 
    return n;
 
 
# Driver Code
n = 31;
print(smallestDivisor(n));
 
# This code is contributed by mits


C#
// C# program to count the number
// of subarrays that having 1
using System;
 
class GFG
{
     
// Function to find the
// smallest divisor
static int smallestDivisor(int n)
{
    // if divisible by 2
    if (n % 2 == 0)
        return 2;
 
    // iterate from 3 to sqrt(n)
    for (int i = 3;
             i * i <= n; i += 2)
    {
        if (n % i == 0)
            return i;
    }
 
    return n;
}
 
// Driver Code
static public void Main ()
{
    int n = 31;
    Console.WriteLine(smallestDivisor(n));
}
}
 
// This code is contributed
// by Sach_Code


PHP


Javascript


输出:
31

如何有效地找到直到n的所有数字的素因数?
请参考数字的最小素因数,直到n

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。