📌  相关文章
📜  查找给定范围内具有至少一个奇数除数的元素

📅  最后修改于: 2021-05-25 04:05:15             🧑  作者: Mango

给定两个整数NM ,任务是打印范围[N,M]中具有至少一个奇数除数的所有元素。
例子:

天真的方法:
最简单的方法是循环遍历[1,N]范围内的所有数字,并针对每个元素检查其是否具有奇数除数。
时间复杂度: O(N 3/2 )
高效方法:
为了优化上述方法,我们需要注意以下细节:

  • 2的幂的任何数字都没有奇数除数。
  • 所有其他元素将至少具有一个奇数除数

请按照以下步骤解决问题:

  • 遍历范围[N,M]并检查每个元素的设置位是否设置为前一个数字,即检查i&(i – 1)是否等于0
  • 如果是这样,则该数字为2的幂,不予考虑。否则,请打印该数字,因为它不是2的幂且具有至少一个奇数除数。

下面是上述方法的实现。

C++
// C++ program to print all numbers
// with least one odd factor in the
// given range
#include 
using namespace std;
 
// Function to prints all numbers
// with at least one odd divisor
int printOddFactorNumber(int n,
                         int m)
{
    for (int i = n; i <= m; i++) {
 
        // Check if the number is
        // not a power of two
        if ((i > 0)
            && ((i & (i - 1)) != 0))
 
            cout << i << " ";
    }
}
 
// Driver Code
int main()
{
    int N = 2, M = 10;
    printOddFactorNumber(N, M);
    return 0;
}


Java
// Java program to print all numbers
// with least one odd factor in the
// given range
class GFG{
 
// Function to prints all numbers
// with at least one odd divisor
static int printOddFactorNumber(int n,
                                int m)
{
    for (int i = n; i <= m; i++)
    {
 
        // Check if the number is
        // not a power of two
        if ((i > 0) && ((i & (i - 1)) != 0))
 
            System.out.print(i + " ");
    }
    return 0;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 2, M = 10;
    printOddFactorNumber(N, M);
}
}
 
// This code is contributed
// by shivanisinghss2110


Python3
# Python3 program to print all numbers
# with least one odd factor in the
# given range
 
# Function to prints all numbers
# with at least one odd divisor
def printOddFactorNumber(n, m):
     
    for i in range(n, m + 1):
 
        # Check if the number is
        # not a power of two
        if ((i > 0) and ((i & (i - 1)) != 0)):
            print(i, end = " ")
             
# Driver Code
N = 2
M = 10
 
printOddFactorNumber(N, M)
 
# This code is contributed by Vishal Maurya


C#
// C# program to print all numbers
// with least one odd factor in the
// given range
using System;
class GFG{
 
// Function to prints all numbers
// with at least one odd divisor
static int printOddFactorNumber(int n,
                                int m)
{
    for (int i = n; i <= m; i++)
    {
 
        // Check if the number is
        // not a power of two
        if ((i > 0) && ((i & (i - 1)) != 0))
 
            Console.Write(i + " ");
    }
    return 0;
}
 
// Driver Code
public static void Main()
{
    int N = 2, M = 10;
    printOddFactorNumber(N, M);
}
}
 
// This code is contributed
// by Code_Mech


Javascript


输出:
3 5 6 7 9 10

时间复杂度: O(N)
辅助空间: O(1)