Count numbers which can be constructed using two numbers in C++

C++Server Side ProgrammingProgramming

We are provided three numbers X, Y and N ( to define range [1,N] ). The goal is to find all the numbers in the range [1,N] that can be constructed using X and Y only any number of times..

For example if X=2 and Y=3. Number 6 can be constructed using 2 thrice ( 2+2+2 ) or 3 twice ( 3+3 ). Similarly 7 can be constructed using 2 twice and 3 once ( 2+2+3 ).

We will do this by subtracting X or Y from each number from 1 to N. If the final number reduces to 0 then increment count.

Let’s understand with examples.

Input 

N=10 X=4, Y=3

Output 

Total numbers constructed using X & Y only: 7

Explanation 

Numbers constructed by 3 and 4 only:
3, 4, 6 (3+3), 7 (3+4), 8 (4+4), 9 (3+3+3), 10 (3+3+4)

Input 

N=10 X=5, Y=4

Output 

Total numbers constructed using X & Y only: 5

Explanation 

Numbers constructed by 4 and 5 only:
4, 5, 8(4+4), 9 (4+5), 10 (5+5)

Approach used in the below program is as follows

  • We take three integers X, Y and N.

  • Function constructNums(int n,int x,int y) returns the count of numbers which can be constructed using x and y only.

  • Take the initial variable count as 0 for such numbers.

  • Traverse range of numbers using for loop. i=1 to i<=n

  • Now for each number num=i, using while loop check if num>0,

  • while(num%x==0) and num is not 0 subtract x from it.

  • while(num%y==0) and num is not 0 subtract y from it.

  • If after subtracting x and y number is non divisible by both and is greater than both.Subtract both x and y from it.

  • If after the outer while loop check if num is 0. Means x, y or both can make num. Increment count.

  • At the end of all loops count will have a total number.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int constructNums(int n,int x,int y){
   int count = 0;
   for (int i = 1; i <= n; i++) {
      int num = i;
      while(num>0){
         while((num%x)==0 && num!=0)
         num-=x;
         while((num%y)==0 && num!=0)
         num-=y;
         if (num>x && num>y)
            num=num-x-y;
         else
            break;
      }
      if (num==0)
         { count++;}
   }
   return count;
}
int main(){
   int N=20;
   int X=5,Y=4;
   cout <<"Total numbers constructed using X & Y only:"<<constructNums(N,X,Y);
   return 0;
}

Output

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

Total numbers constructed using X & Y only:14
raja
Published on 31-Oct-2020 05:14:30
Advertisements