DEV Community

Sowntharya
Sowntharya

Posted on Edited on

A Simple Puzzle to learn Python Loops

problem : 1

Tenali Raman and the Palace Guards

Tenali Raman wishes to meet the King. Before reaching the royal court, he has to pass through many palace gates. A guard is posted at each gate.

Every guard demands a share of whatever reward Tenali Raman receives from the King. Tenali Raman agrees and promises:
"I will give you half of whatever reward I receive from the King."

All the guards allow him to enter. After meeting the King, Tenali Raman receives a reward of 1024 lashes.

Keeping his promise, Tenali Raman shares his reward with the guards. At each gate, he gives half of the lashes he still has to receive to the guard at that gate and proceeds to the next gate.

Write a program to determine:

  1. How many lashes each guard receives.
  2. How many Guards are there if Tenali Raman gets only one lash.

code :

number = 1024
guard = 1

while number >= 1:
    number = number // 2    //floor division

    print("Guard", guard, "gets", number)

    guard += 1

Enter fullscreen mode Exit fullscreen mode

output :
Guard 1 gets 512
Guard 2 gets 256
Guard 3 gets 128
Guard 4 gets 64
Guard 5 gets 32
Guard 6 gets 16
Guard 7 gets 8
Guard 8 gets 4
Guard 9 gets 2
Guard 10 gets 1

Problem : 2

Two trains stop at regular intervals:
Train 1 stops at every 3rd station.
Train 2 stops at every 5th station.
Find:
The first common station where both trains stop.
The last common station where both trains stop.
All common stations where both trains stop.

Note: Total Number of Stations are unknown.

no = 1
last_station = no 
first_station = True
while no <=100: 
    if no%3 == 0 and no % 5 == 0:
        if first_station == True: 
            print('First Station is', no)
            first_station = False
        else:
            print('Common Station is', no)
        last_station = no #15 30    45  60  75  90
    no = no + 1

print('Last Station is', last_station)
Enter fullscreen mode Exit fullscreen mode

understanding purpose :
no = 1
if no%3 == 0 and no % 5 == 0:
print('LCM is', no)
no = no + 1
if no%3 == 0 and no % 5 == 0:
print('LCM is', no)
no = no + 1
if no%3 == 0 and no % 5 == 0:
print('LCM is', no)
no = no + 1
if no%3 == 0 and no % 5 == 0:
print('LCM is', no)
no = no + 1
if no%3 == 0 and no % 5 == 0:
print('LCM is', no)
no = no + 1

Top comments (0)