给定两个整数N和M ,任务是打印范围[N,M]中具有至少一个奇数除数的所有元素。
例子:
Input: N = 2, M = 10
Output: 3 5 6 7 9 10
Explanation:
3, 6 have an odd divisor 3
5, 10 have an odd divisor 5
7 have an odd divisor 7
9 have two odd divisors 3, 9
Input: N = 15, M = 20
Output: 15 17 18 19 20
天真的方法:
最简单的方法是循环遍历[1,N]范围内的所有数字,并针对每个元素检查其是否具有奇数除数。
时间复杂度: O(N 3/2 )
高效方法:
为了优化上述方法,我们需要注意以下细节:
- 2的幂的任何数字都没有奇数除数。
- 所有其他元素将至少具有一个奇数除数
Illustration:
In the range [3, 10], the elements which have at least one odd divisors are {3, 5, 6, 7, 9, 10} and {4, 8} does not contain any odd divisors.
请按照以下步骤解决问题:
- 遍历范围[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)