Ways to paint N paintings such that adjacent paintings don't have same colors in C programming

In this problem, you are given N paintings and we have M colors to paint them with. We need to find the number of ways to paint the paintings such that no two adjacent paintings have the same color.

The program's output can have very large values, so we calculate the answer in standard modulo 109 + 7.

Syntax

long long paintWays(int n, int m);
long long power(long long base, long long exp, long long mod);

Mathematical Formula

The formula to find the number of ways is −

Ways = m * (m-1)^(n-1)

Where:

  • m = number of available colors
  • n = number of paintings
  • (m-1)^(n-1) = each subsequent painting can use any color except the previous one

Example

Let's implement this solution using modular exponentiation to handle large numbers −

#include <stdio.h>
#define MOD 1000000007

long long power(long long base, long long exp, long long mod) {
    long long result = 1;
    base = base % mod;
    while (exp > 0) {
        if (exp & 1)
            result = (result * base) % mod;
        exp = exp >> 1;
        base = (base * base) % mod;
    }
    return result;
}

long long paintWays(int n, int m) {
    if (n == 1) return m;
    return (1LL * m * power(m - 1, n - 1, MOD)) % MOD;
}

int main() {
    int n = 5, m = 6;
    printf("Number of paintings: %d<br>", n);
    printf("Number of colors: %d<br>", m);
    printf("Number of ways to paint: %lld<br>", paintWays(n, m));
    return 0;
}
Number of paintings: 5
Number of colors: 6
Number of ways to paint: 3750

How It Works

  1. For the first painting, we can use any of the m colors
  2. For each subsequent painting, we can use any color except the one used for the previous painting, giving us (m-1) choices
  3. Since we have (n-1) remaining paintings after the first one, the total ways = m × (m-1)^(n-1)
  4. We use modular exponentiation to calculate large powers efficiently

Key Points

  • Time complexity: O(log n) due to fast exponentiation
  • Space complexity: O(1)
  • Handles edge case when n = 1 (only one painting needs m ways)
  • Uses modulo arithmetic to prevent integer overflow

Conclusion

This solution efficiently calculates the number of ways to paint N paintings with M colors such that no adjacent paintings have the same color. The formula m × (m-1)^(n-1) combined with modular exponentiation provides an optimal solution.

Updated on: 2026-03-15T11:29:22+05:30

760 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements