Given a positive integer N, the task is to count the number of integers from the range [1, N], that can be represented as ab, where a and b are integers greater than 1.
Examples:
Input: N = 6
Output: 1
Explanation:
Only such integer from the range [1, 6] is 4 (= 22).
Therefore, the required count is 1.
Input: N = 10
Output: 3
Approach: The given problem can be solved by counting all the possible pairs of elements (a, b) such that ab is at most N. Follow the steps below to solve the problem:
- Initialize a HashSet to store all possible values of ab which is at most N.
- Iterate over the range [2, ?N], and for each value of a, insert all possible values of ab having value at most N, where b lies over the range [1, N].
- After completing the above steps, print the size of the HashSet as the resultant count of integers.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printNumberOfPairs( int N)
{
unordered_set< int > st;
for ( int i = 2; i * i <= N; i++)
{
int x = i;
while (x <= N)
{
x *= i;
if (x <= N)
{
st.insert(x);
}
}
}
cout << st.size();
}
int main()
{
int N = 10000;
printNumberOfPairs(N);
return 0;
}
|
Java
import java.util.HashSet;
public class GFG {
static void printNumberOfPairs( int N)
{
HashSet<Integer> st
= new HashSet<Integer>();
for ( int i = 2 ; i * i <= N; i++) {
int x = i;
while (x <= N) {
x *= i;
if (x <= N) {
st.add(x);
}
}
}
System.out.println(st.size());
}
public static void main(String args[])
{
int N = 10000 ;
printNumberOfPairs(N);
}
}
|
Python3
from math import sqrt
def printNumberOfPairs(N):
st = set ()
for i in range ( 2 , int (sqrt(N)) + 1 , 1 ):
x = i
while (x < = N):
x * = i
if (x < = N):
st.add(x)
print ( len (st))
if __name__ = = '__main__' :
N = 10000
printNumberOfPairs(N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void printNumberOfPairs( int N)
{
HashSet< int > st = new HashSet< int >();
for ( int i = 2; i * i <= N; i++)
{
int x = i;
while (x <= N)
{
x *= i;
if (x <= N)
{
st.Add(x);
}
}
}
Console.WriteLine(st.Count);
}
public static void Main( string [] args)
{
int N = 10000;
printNumberOfPairs(N);
}
}
|
Javascript
<script>
function printNumberOfPairs( N)
{
var st = new Set();
for (let i = 2; i * i <= N; i++) {
let x = i;
while (x <= N) {
x *= i;
if (x <= N) {
st.add(x);
}
}
}
document.write(st.size);
}
let N = 10000;
printNumberOfPairs(N);
</script>
|
Time Complexity: O(N log N)
Auxiliary Space: O(N)