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

C++Server Side ProgrammingProgramming

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,

Input

n = 3, m =3

Output

12

Explanation

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,

n*(m-1)(n-1)

Program to show the implementation of our solution,

Example

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;
}

Output

The number of ways to color the given paintings is : 9072
Published on 17-Jul-2020 11:31:46