Python Program to find out the price of a product after a number of days

Sometimes we need to calculate the price of a product after exponential price increases over multiple days. This problem involves computing modular exponentiation to handle very large numbers efficiently.

Problem Understanding

Given an initial product price x and number of days y, the price after y days becomes x^y. Since this can result in extremely large numbers, we return the result modulo 10^9 + 7.

Algorithm Steps

The solution involves the following steps ?

  • Iterate through each price-days pair in the input list
  • Extract the initial price x and days y from each pair
  • Calculate x^y mod (10^9 + 7) using Python's built-in pow() function
  • Print the result for each pair

Example

Let us see the implementation to calculate exponential price increases ?

def solve(nums):
    results = []
    for i in range(len(nums)):
        x, y = nums[i][0], nums[i][1]
        result = pow(x, y, 1000000007)
        results.append(result)
        print(result)
    return results

# Test with sample data
test_cases = [
    (5, 2),
    (6, 8), 
    (2, 12),
    (2722764242812953792238894584, 3486705296791319646759756475),
    (1505449742164712795427942455727527, 61649494321438487460747056421546274264)
]

solve(test_cases)
25
1679616
4096
754504594
32955023

How It Works

The pow(x, y, mod) function performs modular exponentiation efficiently using the formula:

  • 5^2 = 25
  • 6^8 = 1679616
  • 2^12 = 4096
  • For very large numbers, the result is computed modulo 10^9 + 7 = 1000000007

Alternative Implementation

Here's a cleaner version that returns a list of results ?

def calculate_prices(price_days_pairs):
    MOD = 1000000007
    return [pow(price, days, MOD) for price, days in price_days_pairs]

# Example usage
nums = [(5, 2), (6, 8), (2, 12)]
results = calculate_prices(nums)

for i, result in enumerate(results):
    price, days = nums[i]
    print(f"Price {price} after {days} days: {result}")
Price 5 after 2 days: 25
Price 6 after 8 days: 1679616
Price 2 after 12 days: 4096

Key Points

  • Python's pow(x, y, mod) efficiently computes (x^y) % mod
  • Modulo 10^9 + 7 prevents integer overflow for very large results
  • Time complexity is O(log y) for each exponentiation
  • The algorithm handles arbitrarily large input numbers

Conclusion

Use Python's built-in pow(x, y, mod) function for efficient modular exponentiation. This approach handles exponential price calculations even with extremely large numbers by using modular arithmetic.

Updated on: 2026-03-25T20:27:37+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements