Count numbers from range whose prime factors are only 2 and 3 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 the numbers that have only 2 and 3 as their prime factors and are in the range [START,END].

We will do this by traversing numbers from START to END and for each number we will check if the number is divisible by 2 and 3 only. If divisible, divide it and reduce it. If not, break the loop. In the end if the number is reduced to 1 then it has only 2 and 3 as its factors.

Let’s understand with examples.

Input 

START=20 END=25

Output 

Numbers with only 2 and 3 as prime factors: 1

Explanation 

Prime factors of each number:
20 = 2*2*5
21 = 3*7
22 = 2*11
23 = 1*23
24 = 2*2*2*3
25 = 5*5
Only 24 has 2 and 3 as prime factors.

Input 

START=1000 END=1500

Output 

Numbers with only 2 and 3 as prime factors: 4

Explanation 

1024 1152 1296 1458 are the numbers with only 2 and 3 as prime factors

Approach used in the below program is as follows

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

  • Function twothreeFactors(int start, int end) takes range variables and returns the count of numbers with 2 and 3 as only prime factors.

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

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

  • Now for each number num=i, using while loop check if num%2==0, divide it.

  • if num%3==0, divide it. If not by both break the while loop

  • If after the while loop num is 1 then increase count.

  • At the end of all loops count will have a total number which has only 2 and 4 as prime factors.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int twothreeFactors(int start, int end){
   // Start with 2 so that 1 doesn't get counted
   if (start == 1)
      { start++; }
   int count = 0;
   for (int i = start; i <= end; i++) {
      int num = i;
      while(num>1){
         // if divisible by 2, divide it by 2
         if(num % 2 == 0)
            { num /= 2; }
         // if divisible by 3, divide it by 3
         else if (num % 3 == 0)
            { num /= 3; }
         else //if divisible by neither 2 nor 3 break
            { break; }
      }
      // means only 2 and 3 are factors of num
      if (num == 1)
         { count++; }
   }
   return count;
}
int main(){
   int START = 10, END = 20;
   cout <<"Numbers with only 2 and 3 as prime factors:"<< twothreeFactors(START,END);
   return 0;
}

Output

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

Numbers with only 2 and 3 as prime factors:3
raja
Published on 31-Oct-2020 04:38:19
Advertisements