Counting numbers whose difference from reverse is a product of k in C++

C++Server Side ProgrammingProgramming

We are given a range [l,r] and a number k. The goal is to find all the numbers between l and r (l<=number<=r) such that (reverse of that number)-(number) results into a product of k.

We will check this condition by starting from l to r, calculate the reverse of each number. Now subtract the number from its reverse and check if (absolute difference) %k==0. If yes then increment the count.

Let’s understand with examples.

Input − L=21, R=25, K=6

Output − Count of numbers − 2

Explanation

The numbers their reverse and difference is:
21, 12, | 21-12 |=9, 9%6!=0
22, 22, | 22-22 |=0 0%6=0 count=1
23,32,  | 32-23 | =9 9%6!=0
24,42,  | 42-24 | =18 18%6=0 count=2
25,52,  | 52-25 | =27 27%6!=0
Total numbers that meet the condition are 2 ( 22,24 )

Input − L=11, R=15, K=5

Output − Count of numbers − 1

Explanation

The only number is 11 , | 11-11 | is 0 and 0%5=0

Approach used in the below program is as follows

  • We take an integers L and R to define the range. And K for checking divisibilty.

  • Function countNumbers(int l, int r, int k) takes l,r and k as input and returns the count of numbers that meet the required condition.

  • Take the initial count as 0.

  • Take reverse of number rev=0.

  • Take remainder rem=0.

  • Starting from i= l to i= r.

  • Store current number i in num. And its rev=0.

  • Now reverse the number num, while(num>0). rem=num%10. rev=rev*10+rem. num=num/10.

  • After the end of while rev has reverse of i.

  • Calculate absolute difference of rev and original value i. If this difference | i-rev |%k==0. Then increment the count.

  • Do this for all numbers in the range.

  • Final value of count is returned as numbers whose difference with reverse is the product of k.

Example

 Live Demo

#include <iostream>
using namespace std;
int countNumbers(int l, int r, int k){
   int rev = 0;
   int count=0;
   int rem=0;
   for (int i = l; i <= r; i++){
      int num=i;
      rev=0;
      while (num > 0){
         // reverse the number
         rem=num%10;
         rev = rev * 10 + rem;
         num /= 10;
      }
      if((abs(i-rev))%k==0) //original number is i and its reverse is rev
         { count++; }
   }
   return count;
}
int main(){
   int L= 18, R = 24, K = 6;
   cout <<" Numbers whose difference with reverse is product of k:"<<countNumbers(L,R,K);
   return 0;
}

Output

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

Numbers whose difference with reverse is product of k:4
raja
Published on 29-Aug-2020 09:10:25
Advertisements