703973. Powers game

Easy

Here is a detailed Markdown blog post for the "Powers game" problem:

Powers Game

Summary

The powers game is an algorithmic problem that involves calculating the maximum sum of powers of a given number. The problem requires understanding of modular arithmetic and logical thinking. Given a positive integer n, find the maximum value of n^k modulo 10^9 + 7 for all 1 <= k <= n.

Detailed Explanation

The key to solving this problem is to understand how powers of numbers behave when taken modulo a large number. One way to approach this problem is by using modular arithmetic properties.

Here's the step-by-step breakdown of the solution:

  1. Initialize the maximum sum to 0.
  2. Iterate over all values of k from 1 to n.
  3. For each k, calculate n^k modulo (10^9 + 7). This can be done using the property that (a * b) mod c = ((a mod c) * (b mod c)) mod c.
  4. Add the calculated value to the maximum sum.
  5. Return the maximum sum.

Here's an ASCII art diagram illustrating the steps:

    1. Initialize max_sum
    2. Iterate over k from 1 to n
        3. Calculate n^k mod (10^9 + 7)
            -> ((n mod (10^9 + 7)) * (k mod (10^9 + 7))) mod (10^9 + 7)
        4. Add calculated value to max_sum
    5. Return max_sum

The time complexity of this solution is O(n), where n is the input size, and the space complexity is O(1) as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxPowers(int n) {
    long maxSum = 0;
    for (int k = 1; k <= n; k++) {
        maxSum += pow(n, k, 1000000007);
    }
    return (int)maxSum;
}

private long pow(long a, long b, long mod) {
    long res = 1;
    while (b > 0) {
        if ((b & 1) == 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.