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 n is initialized to 1.

  • A while loop runs until n reaches 50.

  • The condition n % 2 != 0 and n % 3 != 0 checks if the number is not divisible by both 2 and 3.

  • If the condition is true, the number is printed.

  • The variable n is 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.

Updated on: 2026-03-25T19:06:52+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements