- A king announces a unique reward for Hard Workers. On each day, the reward is multiplied by the day's number. The reward starts at 1 gold coin. Given the number of days n, write a program to calculate the final reward. hint: factorial
//JS
let reward = 1;
let n = 5;
let i = 1;
while(i <= n){
reward *= i;
i++;
}
console.log(`${n} days reward = ${reward}`);
#Python
reward = 1
n = 5
i = 1
while i <= n:
reward *= i
i += 1
print(f"{n} days reward = {reward}")
Output: 5 days reward = 120
- Suppose a password consists of the letters: A, B, C, D. Each letter must be used exactly once. How many different passwords are possible? hint: factorial
//JS
let letters = 4;
let result = 1;
let i = 1;
while (i <= letters) {
result *= i;
i++;
}
console.log(result);
#Python
letters = 4
result = 1
i = 1
while i <= letters:
result *= i
i += 1
print(result)
output: 24
- A frog accidentally falls into a 60-foot-deep well.
Every day:
- During the day, the frog climbs 2 feet.
- During the night, it slips down 0.5 feet.
This pattern continues every day until the frog reaches the top of the well and escapes.
Write a program to determine:
- How many days it takes for the frog to get out of the well.
- On which day the frog escapes.
Note: Once the frog reaches or crosses the top of the well during the daytime, it escapes immediately and does not slip back that night.
//JS
let up = 0;
let day = 0;
let n = 60;
while(up<=60){
up = up + 2;
day = day + 1;
if(up >= n){
break;
}
up = up - 0.5;
}
console.log("Number of days:", day);
console.log("Frog escapes on day:", day);
#Python
up = 0
day = 0
n = 60
while up <= 60:
up = up + 2
day = day + 1
if up >= n:
break
up = up - 0.5
print("Number of days:", day)
print("Frog escapes on day:", day)
Output: Number of days: 40
Frog escapes on day: 40
11) The Saint's Flower Basket
A saint goes for a morning walk every day. During his walk, he plucks flowers and keeps them in a basket.
On his way back home, he visits 7 temples. At each temple, he offers half of the flowers currently in his basket.
After visiting all 7 temples, he reaches home with exactly one flower remaining in his basket.
Write a program to determine how many flowers the saint had in his basket before he visited the first temple.
Hint: Think carefully about whether it is easier to solve the problem from the beginning or by working backwards from the final flower.
//JS
let flower = 1;
let temple = 0;
while(temple < 7){
flower = flower *2;
temple += 1;
}
console.log("Total Flowers = " + flower);
#Python
flower = 1
temple = 0
while temple < 7:
flower = flower * 2
temple += 1
print("Total Flowers =", flower)
Output: Total Flowers = 128
Top comments (0)