Maximize profit when divisibility by two numbers have associated profits in C++

We are given with five integers N, A, B, X and Y. The goal is to maximize the profit by checking that between numbers in range [ 1 to N ] , if

  • A number is divisible by A, then profit increases by X.

  • A number is divisible by B then profit increases by Y.

A profit can be added once only, for a particular number in range.

Let’s understand with examples.

Input − N=4, A=2, B=3, X=2, Y=3

Output − Maximized profit is − 7


2,4 are divisible by A ( 2 ). Profit increases from 0 to 2, then 2 to 4 ( by X=2 )

3 is divisible by B ( 3 ). Profit increases from 4 to 7. (by Y=3)

Input − N=5, A=2, B=4, X=1, Y=3

Output − Maximized profit is: 4


2,4 are divisible by A ( 2 ).

4 is also divisible by B ( 4 ).

For 2 profit increases from 0 to 1 (by X). For 4 we chose divisibility by B. So profit increases by Y not X as Y is more. So it rises from 1 to 4 ( by Y=3 ).

Approach used in the below program is as follows

  • We have integers N, A, B, X, Y.

  • Function maximizeProfit(int n, int a, int b, int x, int y) calculates the profit and returns the value. It takes all variables as parameters and return maximized profit.

  • Variable profit will have an amount of profit, initially 0.

  • Starting from 1 to n, check divisibility of i by a and b, using for loop

  • If i is divisible by both a and b then increase profit by x or y whichever is more.

  • Else if i is divisible by a only, increase profit by x

  • Else if i is divisible by b only, increase profit by y

  • At the end return value present in profit as result.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum profit
int maximizeProfit(int n, int a, int b, int x, int y){
   int profit=0;
   for(int i=1;i<=n;i++){
      if(i%a==0 && i%b==0){
         int maxx=x>=y?x:y;
      else if(i%a==0){
      else if(i%b==0){
   return profit;
int main(){
   int N = 6, A = 2, B =4, X = 6, Y = 3;
   cout <<"Maximized profit is: "<<maximizeProfit(N,A,B,X,Y);
   return 0;


If we run the above code it will generate the following output −

Maximized profit is: 2