Ways to paint N paintings such that adjacent paintings don’t have same colors in C++

In this problem, we are given two integers n and m, where n is the number of paintings and m is the number of colors available. Our task is to create a program that will find the total number of ways in which we can paint the paintings in such a way that no to consecutive paintings have the same color.

Let’s take an example to understand the problem,


n = 3, m =3




P1 P2 P3
C1 C2 C3
C1 C3 C2
C1 C2 C1
C1 C3 C1
C2 C1 C2
C2 C3 C2
C2 C1 C3
C2 C3 C1
C3 C1 C3
C3 C2 C3
C3 C1 C2
C3 C2 C1

To solve this problem, we can paint all n paintings with m colors, now the next paintings can be painted using n-1 color excluding the color used to paint the last painting. So, the total number of ways is,


Program to show the implementation of our solution,


 Live Demo

#include <iostream>
#define modd 1000000007
using namespace std;
unsigned long calcPower(unsigned long base, unsigned long power, unsigned long p){
   unsigned long result = 1;
   base = base % p;
   while (power > 0) {
      if (power & 1)
         result = (result * base) % p;
      power = power >> 1;
      base = (base * base) % p;
   return result;
int colorPainting(int n, int m){
   return calcPower(m - 1, n - 1, modd) * m % modd;
int main(){
   int n = 5, m = 7;
   cout<<"The number of ways to color the given paintings is : "<<colorPainting(n, m);
   return 0;


The number of ways to color the given paintings is : 9072

Updated on: 17-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started