Number of elements with even factors in the given range
Last Updated :
23 Jun, 2022
Given a range [n, m], the task is to find the number of elements that have even number of factors in the given range (n and m inclusive).
Examples :
Input: n = 5, m = 20
Output: 14
The numbers with even factors are
5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20.
Input: n = 5, m = 100
Output: 88
A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural number
An Efficient Solution is to find the numbers with odd number of factors i.e only the perfect squares have odd number of factors, so all numbers other than perfect squares will have even number of factors. So, find the count of perfect squares in the range and subtract from the total numbers i.e. m-n+1 .
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countOddSquares( int n, int m)
{
return ( int ) pow (m, 0.5) - ( int ) pow (n - 1, 0.5);
}
int main()
{
int n = 5, m = 100;
cout << "Count is "
<< (m - n + 1) - countOddSquares(n, m);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countOddSquares( int n, int m)
{
return ( int )Math.pow(m, 0.5 ) -
( int )Math.pow(n - 1 , 0.5 );
}
public static void main (String[] args)
{
int n = 5 , m = 100 ;
System.out.println( "Count is " + ((m - n + 1 )
- countOddSquares(n, m)));
}
}
|
Python 3
def countOddSquares(n, m) :
return ( int ( pow (m, 0.5 )) -
int ( pow (n - 1 , 0.5 )))
if __name__ = = "__main__" :
n = 5 ; m = 100 ;
print ( "Count is" , (m - n + 1 ) -
countOddSquares(n, m))
|
C#
using System;
class GFG
{
static int countOddSquares( int n, int m)
{
return ( int )Math.Pow(m, 0.5) -
( int )Math.Pow(n - 1, 0.5);
}
static public void Main ()
{
int n = 5, m = 100;
Console.WriteLine( "Count is " + ((m - n + 1)
- countOddSquares(n, m)));
}
}
|
PHP
<?php
function countOddSquares( $n , $m )
{
return (int)pow( $m , 0.5) -
(int)pow( $n - 1, 0.5);
}
$n = 5;
$m = 100;
echo "Count is " , ( $m - $n + 1) -
countOddSquares( $n , $m );
?>
|
Javascript
<script>
function countOddSquares(n, m)
{
return Math.pow(m,0.5) - Math.pow(n - 1, 0.5);
}
var n = 5, m = 100;
document.write( "Count is "
+ ((m - n + 1) - countOddSquares(n, m)));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...