📌  相关文章
📜  在给定范围内具有偶数因子的元素数

📅  最后修改于: 2021-04-26 07:28:25             🧑  作者: Mango

给定范围[n,m],任务是查找在给定范围内(n和m包括在内)具有偶数个因子的元素数量。

例子 :

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

一个简单的解决方案是遍历从n开始的所有数字。对于每个数字,请检查其是否包含偶数个因子。如果它具有偶数个因子,则增加此类数字的计数,最后打印此类元素的数目。要有效查找自然数的所有除数,请参阅自然数的所有除数

一个有效的解决方案是找到因子数为奇数的数字,即只有理想平方的因子数为奇数,因此除理想平方之外的所有数字的因子数均为偶数。因此,找到该范围内的理想平方数,然后从总数中减去m-n + 1

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
  
// Function to count the perfect squares
int countOddSquares(int n, int m)
{
    return (int)pow(m, 0.5) - (int)pow(n - 1, 0.5);
}
  
// Driver code
int main()
{
    int n = 5, m = 100;
    cout << "Count is "
         << (m - n + 1) - countOddSquares(n, m);
    return 0;
}


Java
// Java implementation of the above approach
import java.io.*;
  
class GFG 
{
      
// Function to count the perfect squares
static int countOddSquares(int n, int m)
{
    return (int)Math.pow(m, 0.5) -
            (int)Math.pow(n - 1, 0.5);
}
  
// Driver code
public static void main (String[] args)
{
    int n = 5, m = 100;
    System.out.println("Count is " + ((m - n + 1)
                    - countOddSquares(n, m)));
}
}
  
// This code is contributed by ajit..


Python 3
# Python3 implementation of the
# above approach 
  
# Function to count the perfect squares 
def countOddSquares(n, m) : 
    return (int(pow(m, 0.5)) - 
            int(pow(n - 1, 0.5))) 
  
# Driver code 
if __name__ == "__main__" :
  
    n = 5 ; m = 100; 
    print("Count is", (m - n + 1) - 
                       countOddSquares(n, m)) 
      
# This code is contributed by Ryuga


C#
// C# implementation of the above approach
using System;
  
class GFG
{
          
// Function to count the perfect squares
static int countOddSquares(int n, int m)
{
    return (int)Math.Pow(m, 0.5) -
            (int)Math.Pow(n - 1, 0.5);
}
  
// Driver code
static public void Main ()
{
    int n = 5, m = 100;
    Console.WriteLine("Count is " + ((m - n + 1)
                    - countOddSquares(n, m)));
}
}
  
// This Code is contributed by akt_mit.


PHP


输出:
Count is 88