
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Winner of Number Reducing Game in Python
Suppose Amal and Bimal are playing a game. They have a number n and they check whether it is a power of 2 or not. If it is, they divide it by 2. otherwise, they reduce it by the next lower number which is also a power of 2. Whoever reduces the number to 1 will win the game. Amal always starts the game, then we have to find the winner's name.
So, if the input is like n = 19, then the output will be Amal because, 19 is not power of 2, so Amal reduces it to 16, then Bimal divides by 2 to make 8, then again Amal divides by 2 to get 4, then Bimal make it 2 and finally Amal divides to make it 1 and wins the game.
To solve this, we will follow these steps −
- res := 0
- while n > 1, do
- b := 1
- while b * 2 < n, do
- b := b * 2
- n := n - b
- res := res + 1
- if res mod 2 is same as 0, then
- return 'Amal'
- otherwise,
- return 'Bmal'
Example
Let us see the following implementation to get better understanding −
def solve(n): res = 0 while(n > 1): b = 1 while(b * 2 < n): b *= 2 n -= b res += 1 if res % 2 == 0: return 'Amal' else: return 'Bmal' n = 19 print(solve(n))
Input
19
Output
Amal
Advertisements