Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Print all Integers that are not Divisible by Either 2 or 3 and Lie between 1 and 50
When it is required to print all integers which are not divisible by either 2 or 3 and lie between 1 and 50, we can use a while loop with conditional statements to check each number. Numbers that satisfy both conditions (not divisible by 2 and not divisible by 3) will be printed.
Example
The following example demonstrates how to find integers between 1 and 50 that are not divisible by either 2 or 3 ?
print("Integers not divisible by 2 and 3, that lie between 1 and 50 are:")
n = 1
while n <= 50:
if n % 2 != 0 and n % 3 != 0:
print(n)
n = n + 1
Integers not divisible by 2 and 3, that lie between 1 and 50 are: 1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49
How It Works
The variable
nis initialized to 1.A while loop runs until
nreaches 50.The condition
n % 2 != 0 and n % 3 != 0checks if the number is not divisible by both 2 and 3.If the condition is true, the number is printed.
The variable
nis incremented by 1 in each iteration.
Using For Loop Alternative
You can also achieve the same result using a for loop with the range() function ?
print("Using for loop:")
for n in range(1, 51):
if n % 2 != 0 and n % 3 != 0:
print(n)
Using for loop: 1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49
Conclusion
Use the modulus operator (%) to check divisibility and combine conditions with and operator. Both while and for loops work effectively for this problem, with for loop being more concise.
