Count numbers in range that are divisible by all of its non-zero digits in C++

C++Server Side ProgrammingProgramming

We are provided two numbers START and END to define a range of numbers.The goal is to find all the numbers in the range [START,END] that are divisible by all of its non-zero digits . We will do this by traversing numbers from START to END and for each number we will check if the number is divisible by all non-zero digits using a while loop. If yes increment count.

Let’s understand with examples.

Input 

START=10 END=20

Output 

Numbers that are divisible by all its non-zero digits: 14

Explanation 

Numbers 10, 11, 12, 15, 20 are divisible by all their non-zero digits.

Input 

START=100 END=200

Output 

Numbers that are divisible by all its non-zero digits: 25

Explanation 

This is list of numbers divisible by all non-zero digits : 100 101 102 104 105 110 111 112 115 120 122 124 126 128 132 135 140 144 150 155 162 168 175 184 200

Approach used in the below program is as follows

  • We take an integer START and END as range variables.

  • Function divisiblebyDigits(int start, int end) takes range variables and returns the count of numbers divisible by all of their non zero digits.

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

  • Take variable flag as 0

  • Traverse range of numbers using for loop. i=start to i=end

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

  • calculate digit=num%10. If digit>0 and i%digit==0 set flag=1. Else flag=0 and break. Reduce num=num/10 to check next digit.

  • If all the non-zero digits fully divide i, flag is 1. Increment count.

  • At the end of all loops count will have a total number which is divisible by non-zero digits

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int divisiblebyDigits(int start, int end){
   int count = 0;
   int flag=0;
   for (int i = start; i <= end; i++){
      int num=i;
      while(num>0){
         int digit=num%10;
         if(digit>0){
            if(i%digit==0)
               { flag=1; } //set flag
            else{
               flag=0; //un-set flag
               break;
            }
         }
         num=num/10;
      }
      if(flag==1) //divisible by all non-zero digits {
         count++;
         //cout<<i<<" ";
      }
   }
   return count;
}
int main(){
   int START = 10, END = 50;
   cout <<"Numbers that are divisible by all its non-zero digits: "<< divisiblebyDigits(START,END);
   return 0;
}

Output

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

Numbers that are divisible by all its non-zero digits: 14
raja
Published on 31-Oct-2020 04:49:43
Advertisements