Contar todos los divisores perfectos de un número

Dado un número n, cuenta los divisores perfectos totales de n. Los divisores perfectos son aquellos divisores que son cuadrados de algún número entero. Por ejemplo, un divisor perfecto de 8 es 4. 

Ejemplos: 

Input  : n = 16 
Output : 3
Explanation : There are only 5 divisor of 16:
1, 2, 4, 8, 16. Only three of them are perfect 
squares: 1, 4, 16. Therefore the answer is 3

Input  : n = 7
Output : 1
 

Enfoque ingenuo

Una fuerza bruta es encontrar todos los divisores de un número . Cuenta todos los divisores que son cuadrados perfectos. 

C++

// Below is C++ code to count total perfect Divisors
#include<bits/stdc++.h>
using namespace std;
 
// Utility function to check perfect square number
bool isPerfectSquare(int n)
{
    int sq = (int) sqrt(n);
    return (n == sq * sq);
}
 
// Returns count all perfect divisors of n
int countPerfectDivisors(int n)
{
    // Initialize result
    int count = 0;
 
    // Consider every number that can be a divisor
    // of n
    for (int i=1; i*i <= n; ++i)
    {
        // If i is a divisor
        if (n%i == 0)
        {
            if (isPerfectSquare(i))
                ++count;
            if (n/i != i && isPerfectSquare(n/i))
                ++count;
        }
    }
    return count;
}
 
// Driver code
int main()
{
    int n = 16;
 
    cout << "Total perfect divisors of "
         << n << " = " << countPerfectDivisors(n) << "\n";
 
    n = 12;
    cout << "Total perfect divisors of "
         << n << " = " << countPerfectDivisors(n);
 
    return 0;
}

Java

// Java code to count
// total perfect Divisors
import java.io.*;
 
class GFG
{
     
// Utility function to check
// perfect square number
static boolean isPerfectSquare(int n)
{
    int sq = (int) Math.sqrt(n);
    return (n == sq * sq);
}
 
// Returns count all
// perfect divisors of n
static int countPerfectDivisors(int n)
{
    // Initialize result
    int count = 0;
 
    // Consider every number
    // that can be a divisor of n
    for (int i = 1; i * i <= n; ++i)
    {
        // If i is a divisor
        if (n % i == 0)
        {
            if (isPerfectSquare(i))
                ++count;
            if (n / i != i &&
                isPerfectSquare(n / i))
                ++count;
        }
    }
    return count;
}
 
// Driver code
public static void main (String[] args)
{
    int n = 16;
 
    System.out.print("Total perfect " +
                   "divisors of " + n);
    System.out.println(" = " +
               countPerfectDivisors(n));
 
    n = 12;
    System.out.print("Total perfect " +
                   "divisors of " + n);
    System.out.println(" = " +
               countPerfectDivisors(n));
}
}
 
// This code is contributed by ajit

Python3

# Python3 implementation of Naive method
# to count all perfect divisors
 
import math
 
def isPerfectSquare(x) :
    sq = (int)(math.sqrt(x))
    return (x == sq * sq)
 
# function to count all perfect divisors
def countPerfectDivisors(n) :
     
    # Initialize result
    cnt = 0
 
        # Consider every number that
        # can be a divisor of n
    for i in range(1, (int)(math.sqrt(n)) + 1) :
 
            # If i is a divisor
            if ( n % i == 0 ) :
 
                if isPerfectSquare(i):
                        cnt = cnt + 1
                if n/i != i and isPerfectSquare(n/i):
                        cnt = cnt + 1
    return cnt
     
         
# Driver program to test above function
print("Total perfect divisor of 16 = ",
    countPerfectDivisors(16))
     
print("Total perfect divisor of 12 = ",
    countPerfectDivisors(12))   
 
# This code is contributed by Saloni Gupta

C#

// C# code to count
// total perfect Divisors
using System;
 
class GFG
{
     
// Utility function to check
// perfect square number
static bool isPerfectSquare(int n)
{
    int sq = (int) Math.Sqrt(n);
    return (n == sq * sq);
}
 
// Returns count all
// perfect divisors of n
static int countPerfectDivisors(int n)
{
    // Initialize result
    int count = 0;
 
    // Consider every number
    // that can be a divisor of n
    for (int i = 1;
             i * i <= n; ++i)
    {
        // If i is a divisor
        if (n % i == 0)
        {
            if (isPerfectSquare(i))
                ++count;
            if (n / i != i &&
                isPerfectSquare(n / i))
                ++count;
        }
    }
    return count;
}
 
// Driver code
static public void Main ()
{
    int n = 16;
     
    Console.Write("Total perfect " +
                "divisors of " + n);
    Console.WriteLine(" = " +
            countPerfectDivisors(n));
     
    n = 12;
    Console.Write("Total perfect " +
                "divisors of " + n);
    Console.WriteLine(" = " +
            countPerfectDivisors(n));
}
}
 
// This code is contributed
// by akt_mit

PHP

<?php
// PHP code to count
// total perfect Divisors
 
// function to check
// perfect square number
function isPerfectSquare($n)
{
    $sq = sqrt($n);
    return ($n == $sq * $sq);
}
 
// Returns count all
// perfect divisors of n
function countPerfectDivisors($n)
{
     
    // Initialize result
    $count = 0;
 
    // Consider every number
    // that can be a divisor
    // of n
    for ($i = 1; $i * $i <= $n; ++$i)
    {
         
        // If i is a divisor
        if ($n % $i == 0)
        {
            if (isPerfectSquare($i))
                ++$count;
            if ($n / $i != $i &&
                isPerfectSquare($n / $i))
                ++$count;
        }
    }
    return $count;
}
 
    // Driver Code
    $n = 16;
    echo "Total perfect divisors of ",
         $n, " = ", countPerfectDivisors($n), "\n";
 
    $n = 12;
    echo "Total perfect divisors of ",
         $n, " = ", countPerfectDivisors($n);
 
// This code is contributed by ajit
?>

Javascript

<script>
 
// JavaScript program for the above approach
 
// Utility function to check
// perfect square number
function isPerfectSquare(n)
{
    let sq = Math.sqrt(n);
    return (n == sq * sq);
}
 
// Returns count all
// perfect divisors of n
function countPerfectDivisors(n)
{
 
    // Initialize result
    let count = 0;
 
    // Consider every number
    // that can be a divisor of n
    for (let i = 1; i * i <= n; ++i)
    {
     
        // If i is a divisor
        if (n % i == 0)
        {
            if (isPerfectSquare(i))
                ++count;
            if (n / i != i &&
                isPerfectSquare(n / i))
                ++count;
        }
    }
    return count;
}
 
// Driver Code
    let n = 16;
 
    document.write("Total perfect " +
                   "divisors of " + n);
    document.write(" = " +
               countPerfectDivisors(n) + "<br/>");
    n = 12;
    document.write("Total perfect " +
                   "divisors of " + n);
    document.write(" = " +
               countPerfectDivisors(n));
 
// This code is contributed by chinmoy1997pal.
</script>
Output:
Total Perfect divisors of 16 = 3
Total Perfect divisors of 12 = 2

Complejidad temporal: O(sqrt(n)) 
Espacio auxiliar: O(1)
 

Enfoque eficiente (para un gran número de consultas)

La idea se basa en el tamiz de Eratóstenes . Este enfoque es beneficioso si hay una gran cantidad de consultas. El siguiente es el algoritmo para encontrar todos los divisores perfectos hasta n números. 

  1. Crea una lista de n enteros consecutivos del 1 al n:(1, 2, 3, …, n)
  2. Inicialmente, sea d 2, el primer divisor
  3. A partir de 4 (cuadrado de 2), incremente todos los múltiplos de 4 en 1 en la array perfectDiv[], ya que todos estos múltiplos contienen 4 como divisor perfecto. Estos números serán 4d, 8d, 12d,…etc
  4. Repita el paso 3 para todos los demás números. La array final de perfectDiv[] contendrá todo el recuento de divisores perfectos del 1 al n

A continuación se muestra la implementación de los pasos anteriores.  

C++

// Below is C++ code to count total perfect
// divisors
#include<bits/stdc++.h>
using namespace std;
#define MAX 100001
 
int perfectDiv[MAX];
 
// Pre-compute counts of all perfect divisors
// of all numbers upto MAX.
void precomputeCounts()
{
    for (int i=1; i*i < MAX; ++i)
    {
        // Iterate through all the multiples of i*i
        for (int j=i*i; j < MAX; j += i*i)
 
            // Increment all such multiples by 1
            ++perfectDiv[j];
    }
}
 
// Returns count of perfect divisors of n.
int countPerfectDivisors(int n)
{
    return perfectDiv[n];
}
 
// Driver code
int main()
{
    precomputeCounts();
 
    int n = 16;
    cout << "Total perfect divisors of "
         << n << " = " << countPerfectDivisors(n) << "\n";
 
    n = 12;
    cout << "Total perfect divisors of "
         << n << " = " << countPerfectDivisors(n);
 
    return 0;
}

Java

// Java code to count total perfect
// divisors
class GFG
{
     
static int MAX = 100001;
 
static int[] perfectDiv = new int[MAX];
 
// Pre-compute counts of all perfect divisors
// of all numbers upto MAX.
static void precomputeCounts()
{
    for (int i = 1; i * i < MAX; ++i)
    {
        // Iterate through all the multiples of i*i
        for (int j = i * i; j < MAX; j += i * i)
 
            // Increment all such multiples by 1
            ++perfectDiv[j];
    }
}
 
// Returns count of perfect divisors of n.
static int countPerfectDivisors(int n)
{
    return perfectDiv[n];
}
 
// Driver code
public static void main (String[] args)
{
    precomputeCounts();
 
    int n = 16;
    System.out.println("Total perfect divisors of " +
                    n + " = " + countPerfectDivisors(n));
 
    n = 12;
    System.out.println("Total perfect divisors of " +
                        n + " = " + countPerfectDivisors(n));
}
}
 
// This code is contributed by mits

Python3

# Below is Python3 code to count total perfect
# divisors
MAX = 100001
  
perfectDiv= [0]*MAX
  
# Pre-compute counts of all perfect divisors
# of all numbers upto MAX.
def precomputeCounts():
 
    i=1
    while i*i < MAX:
     
        # Iterate through all the multiples of i*i
        for j in range(i*i,MAX,i*i):
  
            # Increment all such multiples by 1
            perfectDiv[j] += 1
        i += 1
  
# Returns count of perfect divisors of n.
def countPerfectDivisors( n):
 
    return perfectDiv[n]
  
# Driver code
if __name__ == "__main__":
 
    precomputeCounts()
  
    n = 16
    print ("Total perfect divisors of "
         , n , " = " ,countPerfectDivisors(n))
  
    n = 12
    print ( "Total perfect divisors of "
         ,n ," = " ,countPerfectDivisors(n))

C#

// C# code to count total perfect
// divisors
using System;
class GFG
{
     
static int MAX = 100001;
 
static int[] perfectDiv = new int[MAX];
 
// Pre-compute counts of all perfect
// divisors of all numbers upto MAX.
static void precomputeCounts()
{
    for (int i = 1; i * i < MAX; ++i)
    {
        // Iterate through all the multiples of i*i
        for (int j = i * i; j < MAX; j += i * i)
 
            // Increment all such multiples by 1
            ++perfectDiv[j];
    }
}
 
// Returns count of perfect divisors of n.
static int countPerfectDivisors(int n)
{
    return perfectDiv[n];
}
 
// Driver code
public static void Main()
{
    precomputeCounts();
 
    int n = 16;
    Console.WriteLine("Total perfect divisors of " + n +
                       " = " + countPerfectDivisors(n));
 
    n = 12;
    Console.WriteLine("Total perfect divisors of " + n +
                       " = " + countPerfectDivisors(n));
}
}
 
// This code is contributed by mits

PHP

<?php
// Below is PHP code to count total
// perfect divisors
 
$MAX = 10001;
 
$perfectDiv = array_fill(0, $MAX, 0);
 
// Pre-compute counts of all perfect
// divisors of all numbers upto MAX.
function precomputeCounts()
{
    global $MAX, $perfectDiv;
    for ($i = 1; $i * $i < $MAX; ++$i)
    {
        // Iterate through all the multiples
        // of i*i
        for ($j = $i * $i;
             $j < $MAX; $j += $i * $i)
 
            // Increment all such multiples by 1
            ++$perfectDiv[$j];
    }
}
 
// Returns count of perfect divisors of n.
function countPerfectDivisors($n)
{
    global $perfectDiv;
    return $perfectDiv[$n];
}
 
// Driver code
precomputeCounts();
 
$n = 16;
echo "Total perfect divisors of " . $n .
     " = " . countPerfectDivisors($n) . "\n";
 
$n = 12;
echo "Total perfect divisors of " . $n .
     " = " . countPerfectDivisors($n);
 
// This code is contributed by mits
?>

Javascript

<script>
 
// Javascript code to count total perfect
// divisors
let MAX = 100001;;
let perfectDiv = new Array(MAX);
for(let i = 0; i < MAX; i++)
{
    perfectDiv[i] = 0;
}
 
// Pre-compute counts of all perfect divisors
// of all numbers upto MAX.
function precomputeCounts()
{
    for(let i = 1; i * i < MAX; ++i)
    {
         
        // Iterate through all the multiples of i*i
        for(let j = i * i; j < MAX; j += i * i)
     
            // Increment all such multiples by 1
            ++perfectDiv[j];
    }
}
 
// Returns count of perfect divisors of n.
function countPerfectDivisors(n)
{
    return perfectDiv[n];
}
 
// Driver code
precomputeCounts();
 
let n = 16;
document.write("Total perfect divisors of " +
               n + " = " +
               countPerfectDivisors(n) + "<br>");
 
n = 12;
document.write("Total perfect divisors of " +
               n + " = " +
               countPerfectDivisors(n));
 
// This code is contributed by rag2127
 
</script>

Producción: 

Total Perfect divisors of 16 = 3
Total Perfect divisors of 12 = 2

Complejidad de tiempo: O(MAX * log(log (MAX))) 
Espacio auxiliar: O(MAX)

Este artículo es una contribución de Shubham Bansal . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *