DEV Community

Sowntharya
Sowntharya

Posted on

Puzzles to learn python loops

Problem : 1
Divide the Tiles Equally
A school is preparing a large square floor for its annual function. The floor has N tiles arranged in a single row. The teacher wants to divide these tiles into equal-sized groups without leaving any tile unused. For example, if there are 12 tiles, the teacher can make:

1 group of 12 tiles
2 groups of 6 tiles
3 groups of 4 tiles
4 groups of 3 tiles
6 groups of 2 tiles
12 groups of 1 tile

no = 12
divisor = 1
while divisor <= 12:
    if no % divisor == 0:
        print(divisor)
    divisor = divisor + 1
Enter fullscreen mode Exit fullscreen mode

Problem : 2
The Special Lock Number

A treasure box has a number lock with a number N. The lock designer follows a special rule: A number is considered a Special Number if it can be divided equally into groups in only two ways:
One group containing all the items.
Groups containing one item each.
For example, if the number is 7, the items can be arranged equally only as:
1 group of 7 or 7 groups of 1. But if the number is 8, it can also be arranged as 2 groups of 4, so it is not a Special Number.

Write a Python program that accepts a number N and determines whether it is a Special Number or not.

N = int(input("Enter a number: "))

divisor = 1
count = 0

while divisor <= N:
    if N % divisor == 0:
        count = count + 1
    divisor = divisor + 1

if count == 2:
    print("Special Number")
else:
    print("Not a Special Number")
Enter fullscreen mode Exit fullscreen mode

Problem : 3
Secret VIP Numbers

A security system assigns special numbers to the first few VIP lockers. A number is considered a VIP number if it can be divided exactly by only 1 and itself. The security officer wants the numbers of the first 5 VIP lockers. Write a Python program to display those 5 numbers.

num = 2
count = 0

while count < 5:
    divisor = 1
    factors = 0

    while divisor <= num:
        if num % divisor == 0:
            factors = factors + 1
        divisor = divisor + 1

    if factors == 2:
        print(num)     // 2 3 5 7 11
        count = count + 1

    num = num + 1

Enter fullscreen mode Exit fullscreen mode

Problem : 4
16.2) The Special Numbers
A teacher is preparing a Number Exhibition for students. She writes the numbers 1 to 20 on 20 cards. She wants to select only the special cards. A card is special if its number can be divided exactly by only two numbers: 1 and the number itself.

The teacher asks the students:
“Check all the cards from 1 to 20 and display the numbers that are special.”

num = 1

while num <= 20:
    divisor = 1
    count = 0

    while divisor <= num:
        if num % divisor == 0:
            count = count + 1
        divisor = divisor + 1

    if count == 2:
        print(num)  //2 3 5 7 11 13 17 19
    num = num + 1

Enter fullscreen mode Exit fullscreen mode

Top comments (0)