Count numbers from range whose prime factors are only 2 and 3
Given two positive integers L and R, the task is to count the elements from the range [L, R] whose prime factors are only 2 and 3.
Examples:
Input: L = 1, R = 10
Output: 6
2 = 2
3 = 3
4 = 2 * 2
6 = 2 * 3
8 = 2 * 2 * 2
9 = 3 * 3
Input: L = 100, R = 200
Output: 5
Approach: Start a loop from L to R and for every element num:
- While num is divisible by 2, divide it by 2.
- While num is divisible by 3, divide it by 3.
- If num = 1 then increment the count as num has only 2 and 3 as its prime factors.
Print the count in the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findTwoThreePrime( int l, int r)
{
if (l == 1)
l++;
int count = 0;
for ( int i = l; i <= r; i++) {
int num = i;
while (num % 2 == 0)
num /= 2;
while (num % 3 == 0)
num /= 3;
if (num == 1)
count++;
}
return count;
}
int main()
{
int l = 1, r = 10;
cout << findTwoThreePrime(l, r);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int findTwoThreePrime( int l, int r)
{
if (l == 1 )
l++;
int count = 0 ;
for ( int i = l; i <= r; i++) {
int num = i;
while (num % 2 == 0 )
num /= 2 ;
while (num % 3 == 0 )
num /= 3 ;
if (num == 1 )
count++;
}
return count;
}
public static void main (String[] args) {
int l = 1 , r = 10 ;
System.out.println (findTwoThreePrime(l, r));
}
}
|
Python3
def findTwoThreePrime(l, r) :
if (l = = 1 ) :
l + = 1
count = 0
for i in range (l, r + 1 ) :
num = i
while (num % 2 = = 0 ) :
num / / = 2 ;
while (num % 3 = = 0 ) :
num / / = 3
if (num = = 1 ) :
count + = 1
return count
if __name__ = = "__main__" :
l = 1
r = 10
print (findTwoThreePrime(l, r))
|
C#
using System;
class GFG
{
static int findTwoThreePrime( int l, int r)
{
if (l == 1)
l++;
int count = 0;
for ( int i = l; i <= r; i++)
{
int num = i;
while (num % 2 == 0)
num /= 2;
while (num % 3 == 0)
num /= 3;
if (num == 1)
count++;
}
return count;
}
static public void Main ()
{
int l = 1, r = 10;
Console.WriteLine(findTwoThreePrime(l, r));
}
}
|
PHP
<?php
function findTwoThreePrime( $l , $r )
{
if ( $l == 1)
$l ++;
$count = 0;
for ( $i = $l ; $i <= $r ; $i ++)
{
$num = $i ;
while ( $num % 2 == 0)
$num /= 2;
while ( $num % 3 == 0)
$num /= 3;
if ( $num == 1)
$count ++;
}
return $count ;
}
$l = 1;
$r = 10;
echo findTwoThreePrime( $l , $r );
?>
|
Javascript
<script>
function findTwoThreePrime(l, r)
{
if (l == 1)
l++;
let count = 0;
for (let i = l; i <= r; i++)
{
let num = i;
while (num % 2 == 0)
num = parseInt(num / 2, 10);
while (num % 3 == 0)
num = parseInt(num / 3, 10);
if (num == 1)
count++;
}
return count;
}
let l = 1, r = 10;
document.write(findTwoThreePrime(l, r));
</script>
|
Time Complexity: O((r-l)*log2(r-l))
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
08 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...