easy
0 views

Money with Baba

Calculate the initial amount of money Baba had before donating to beggars

Understand the Problem

Problem Statement

Baba is very kind to beggars and every day Baba donates half of the amount he has when ever a beggar requests him. The money M left in Baba's hand is passed as the input and the number of beggars B who received the alms are passed as the input. The program must print the money Baba had in the beginning of the day.

Constraints

  • Money left (M) must be a non-negative integer
  • Number of beggars (B) must be a non-negative integer
  • Initial money will not exceed standard integer limits
  • If M or B is 0, Baba had 0 money initially

Examples

Example 1
Input
100
2
Output
400
Explanation

Baba donated to two beggars. After giving to the second beggar, he had Rs.100. Before that donation, he had 100×2 = Rs.200. Before the first donation, he had 200×2 = Rs.400. So Baba started with Rs.400.

Solution

#include <stdio.h>
#include <math.h>

int main() {
    int M, B;
    scanf("%d", &M);
    scanf("%d", &B);
    
    if (M == 0 || B == 0) {
        printf("0\n");
    } else {
        int initial = M * (int)pow(2, B);
        printf("%d\n", initial);
    }
    
    return 0;
}
Time:O(1) - Constant time using mathematical power function
Space:O(1) - Constant space, only using a few variables
Approach:

Step-by-step explanation:

  • Include necessary headers: stdio.h for input/output and math.h for the pow() function
  • Declare variables M (money left) and B (number of beggars)
  • Read input values using scanf()
  • Check edge case: if either M or B is 0, Baba had 0 money initially
  • Otherwise, calculate initial money as M × 2^B using pow() function
  • Print the result using printf()

Visual Explanation

Loading diagram...