📜  C程序查找数的最大素数

📅  最后修改于: 2021-05-28 05:07:12             🧑  作者: Mango

给定正整数’n’(1 <= n <= 10 15 )。找到一个数字的最大素数。

Input: 6
Output: 3
Explanation
Prime factor of 6 are- 2, 3
Largest of them is '3'

Input: 15
Output: 5
// C Program to find largest prime
// factor of number
#include 
#include 
  
// A function to find largest prime factor
long long maxPrimeFactors(long long n)
{
    // Initialize the maximum prime factor
    // variable with the lowest one
    long long maxPrime = -1;
  
    // Print the number of 2s that divide n
    while (n % 2 == 0) {
        maxPrime = 2;
        n >>= 1; // equivalent to n /= 2
    }
  
    // n must be odd at this point, thus skip
    // the even numbers and iterate only for
    // odd integers
    for (int i = 3; i <= sqrt(n); i += 2) {
        while (n % i == 0) {
            maxPrime = i;
            n = n / i;
        }
    }
  
    // This condition is to handle the case
    // when n is a prime number greater than 2
    if (n > 2)
        maxPrime = n;
  
    return maxPrime;
}
  
// Driver program to test above function
int main()
{
    long long n = 15;
    printf("%lld\n", maxPrimeFactors(n));
  
    n = 25698751364526;
    printf("%lld", maxPrimeFactors(n));
  
    return 0;
}
输出:
5
328513

时间复杂度: \text{O}(\sqrt{n})
辅助空间: \text{O}(1)

请参阅有关查找数字的最大素数的完整文章,以了解更多详细信息!

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。