![]() |
VOOZH | about |
Given a range of numbers, the task is to print all odd numbers within that range. An odd number is any number that is not divisible by 2 (i.e., gives remainder 1 when divided by 2).
For example:
Range: 1 to 10 -> Odd numbers = 1, 3, 5, 7, 9
Range: 5 to 15 -> Odd numbers = 5, 7, 9, 11, 13, 15
Let’s explore different methods to print all odd numbers within a range.
This method directly generates odd numbers using range() function with a step value of 2. By starting from the first odd number, it automatically skips all even numbers, making it highly efficient.
1 3 5 7 9
Explanation:
Bitwise AND operator is useful when we need to check if a number is odd or even. The binary representation of an odd number always ends in 1, while an even number ends in 0. So, we can check if a number is odd by using num & 1.
1 3 5 7 9
Explanation:
Here we creates a list of odd numbers in one line using list comprehension with a conditional check num% 2 ! = 0.
[1, 3, 5, 7, 9]
This is the basic approach. It iterates through the range and checks if each number gives a remainder of 1 when divided by 2.
1 3 5 7 9