Given a positive integer n. Find the value of
donde la función F(i) para el número i se define como la suma de todos los divisores de ‘ i ‘.
Ejemplos:
Input: 4 Output: 15 Explanation F(1) = 1 F(2) = 1 + 2 = 3 F(3) = 1 + 3 = 4 F(4) = 1 + 2 + 4 = 7 ans = F(1) + F(2) + F(3) + F(4) = 1 + 3 + 4 + 7 = 15 Input: 5 Output: 21
El enfoque ingenuo es recorrer para cada número (1 a n), encontrar todos los divisores y seguir actualizando la suma con ese divisor. Mira esto para entender más.
C++
// C++ program to find sum of all // divisor of number up to 'n' #include<bits/stdc++.h> using namespace std; // Utility function to find sum of // all divisor of number up to 'n' int divisorSum(int n) { int sum = 0; for(int i = 1; i <= n; ++i) { // Find all divisors of i and add them for(int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code int main() { int n = 4; cout << " " << divisorSum(n) << endl; n = 5; cout << " " << divisorSum(n); return 0; }
Java
// JAVA program to find sum of all // divisor of number up to 'n' import java.io.*; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code public static void main(String args[]) { int n = 4; System.out.println(divisorSum(n)); n = 5; System.out.println(divisorSum(n)); } } /*This code is contributed by Nikita tiwari.*/
Python3
# Python3 code to find sum of all # divisor of number up to 'n' # Utility function to find sum of # all divisor of number up to 'n' def divisorSum( n ): sum = 0 for i in range(1, n + 1): # Find all divisors of i # and add them j = 1 while j * j <= i: if i % j == 0: if i / j == j: sum += j else: sum += j + i / j j = j + 1 return int(sum) # Driver code n = 4 print( divisorSum(n)) n = 5 print( divisorSum(n)) # This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to find sum of all // divisor of number up to 'n' using System; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code public static void Main() { int n = 4; Console.WriteLine(divisorSum(n)); n = 5; Console.WriteLine(divisorSum(n)); } } /*This code is contributed by vt_m.*/
PHP
<?php // PHP program to find sum of all // divisor of number up to 'n' // Utility function to find sum of // all divisor of number up to 'n' function divisorSum($n) { $sum = 0; for ($i = 1; $i <= $n; ++$i) { // Find all divisors of i // and add them for ($j = 1; $j * $j <= $i; ++$j) { if ($i % $j == 0) { if ($i / $j == $j) $sum += $j; else $sum += $j + $i / $j; } } } return $sum; } // Driver code $n = 4; echo "\n", divisorSum($n), "\n"; $n = 5; echo divisorSum($n), "\n"; // This code is contributed by aj_36 ?>
Javascript
<script> // Javascript program to find sum of all // divisor of number up to 'n' // Utility function to find sum of // all divisor of number up to 'n' function divisorSum(n) { let sum = 0; for (let i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (let j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code let n = 4; document.write(divisorSum(n) + "<br>"); n = 5; document.write(divisorSum(n) + "<br>"); // This code is contributed by _saurabh_jaiswal </script>
Producción :
15 21
Complejidad temporal: O(n√(n)))
Espacio auxiliar: O(1)
El enfoque eficiente es observar la función y correlacionar el patrón. Para un número n dado, todo número del 1 al n contribuye con su presencia hasta el mayor múltiplo menor que n. Por ejemplo,
Let n = 6, => F(1) + F(2) + F(3) + F(4) + F(5) + F(6) => 1 will occurs 6 times in F(1), F(2), F(3), F(4), F(5) and F(6) => 2 will occurs 3 times in F(2), F(4) and F(6) => 3 will occur 2 times in F(3) and F(6) => 4 will occur 1 times in F(4) => 5 will occur 1 times in F(5) => 6 will occur 1 times in F(6)
De la observación anterior, se puede observar fácilmente que el número i ocurre solo en sus múltiplos menores o iguales que n . Por lo tanto, solo necesitamos encontrar el conteo de múltiplos y luego multiplicarlo con i para obtener la contribución total en la suma final. Se puede hacer fácilmente en tiempo O(1) tomando el piso de (n / i) y luego multiplicándolo con i para la suma.
C++
// C++ program to find sum of all // divisor of number up to 'n' #include<bits/stdc++.h> using namespace std; // Utility function to find sum of // all divisor of number up to 'n' int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code int main() { int n = 4; cout <<" "<< divisorSum(n)<<endl; n = 5; cout <<" "<< divisorSum(n)<< endl; return 0; } // This code is contributed by shivanisinghss2110
C
// C program to find sum of all // divisor of number up to 'n' #include <stdio.h> // Utility function to find sum of // all divisor of number up to 'n' int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code int main() { int n = 4; printf("%d\n", divisorSum(n)); n = 5; printf("%d", divisorSum(n)); return 0; }
Java
// Java program to find sum of all // divisor of number up to 'n' import java.io.*; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code public static void main(String args[]) { int n = 4; System.out.println(divisorSum(n)); n = 5; System.out.println(divisorSum(n)); } } /*This code is contributed by Nikita Tiwari.*/
Python3
# Python3 code to find sum of all # divisor of number up to 'n' # Utility function to find sum of # all divisor of number up to 'n' def divisorSum( n ): sum = 0 for i in range(1, n + 1): sum += int(n / i) * i return int(sum) # Driver code n = 4 print( divisorSum(n)) n = 5 print( divisorSum(n)) # This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to find sum of all // divisor of number up to 'n' using System; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code public static void Main() { int n = 4; Console.WriteLine(divisorSum(n)); n = 5; Console.WriteLine(divisorSum(n)); } } /*This code is contributed by vt_m.*/
PHP
<?php // PHP program to find sum of all // divisor of number up to 'n' // Utility function to find sum of // all divisor of number up to 'n' function divisorSum( $n) { $sum = 0; for ( $i = 1; $i <= $n; ++$i) $sum += floor($n / $i) * $i; return $sum; } // Driver code $n = 4; echo divisorSum($n),"\n"; $n = 5; echo divisorSum($n),"\n"; // This code is contributed by anuj_67. ?>
Javascript
// Javascript program to find sum of all // divisor of number up to 'n' // Utility function to find sum of // all divisor of number up to 'n' function divisorSum(n) { let sum = 0; for (let i = 1; i <= n; ++i) sum += Math.floor(n / i) * i; return sum; } // Driver code let n = 4; document.write(divisorSum(n) + "<br>"); n = 5; document.write(divisorSum(n) + "<br>"); // This code is contributed by _saurabh_jaiswal.
Producción :
15 21
Complejidad temporal: O(n)
Espacio auxiliar: O(1)
Solución más eficiente:
tenemos que calcular
Para evaluar la expresión anterior en O(sqrt(N)) hacemos uso del lema armónico.
Considere la secuencia armónica en la división de enteros: {N/1, N/2, N/3, ….. ,N/N}
El lema establece que la sucesión anterior no es creciente y que hay como máximo 2*sqrt(N) elementos diferentes.
Considere piso(N/i) = k. Así, k <= N/i < k+1. De esto obtenemos mayor = piso (N/k). Por lo tanto, podemos encontrar un rango de valores de i para el cual piso(N/i) es constante. Y usando The Harmonic Lemma sabemos que serán como máximo 2*sqrt(N) términos, por lo que podemos calcularlo programáticamente en O(sqrt(N)) complejidad. Considere el siguiente ejemplo para una mejor aclaración.
C++
// C++ program to calculate sum of divisors // of numbers from 1 to N in O(sqrt(N)) complexity #include <iostream> using namespace std; #define ll long long #define mod 1000000007 /* Function to calculate x^y using Modular exponentiation Refer to https://www.geeksforgeeks.org/ modular-exponentiation-power-in-modular-arithmetic/ */ ll power(ll x, ll y, ll p) { // re x^y if p not specified // else (x^y)%p ll res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p; } // Function to find modular // inverse of a under modulo m // Assumption: m is prime ll modinv(ll x) { return power(x, mod - 2, mod); } // Function to calculate sum from 1 to n ll sum(ll n) { // sum 1 to n = (n*(n+1))/2 ll retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval; } ll divisorSum(ll n) { ll l = 1; ll ans = 0; while (l <= n) { ll k = n / l; ll r = n / k; k %= mod; // For i=l to i=r, floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very large // we need to take mod at every step ans %= mod; l = r + 1; } ans = ans % mod; // ans can be negative // for example n = 831367 ans would be -534577982 if (ans < 0){ return ans+mod; }else{ return ans; } } /* Driver program to test above function */ int main() { int n = 5; cout << "The sum of divisors of all \ numbers from 1 to " << n << " is: " \ << divisorSum(n) << '\n'; n = 14; cout << "The sum of divisors of all \ numbers from 1 to " << n << " is: " \ << divisorSum(n) << '\n'; }
Java
// Java program to calculate // sum of divisors of numbers // from 1 to N in O(sqrt(N)) // complexity import java.util.*; class Main{ static int mod = 1000000007; /* Function to calculate x^y using Modular exponentiation Refer to https://www.geeksforgeeks.org/ modular-exponentiation-power-in- modular-arithmetic/ */ public static long power(long x, long y, long p) { // re x^y if p not specified // else (x^y)%p long res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p; } // Function to find modular // inverse of a under modulo m // Assumption: m is prime public static long modinv(long x) { return power(x, mod - 2, mod); } // Function to calculate sum // from 1 to n public static long sum(long n) { // sum 1 to n = (n*(n+1))/2 long retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval; } public static long divisorSum(long n) { long l = 1; long ans = 0; while (l <= n) { long k = n / l; long r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans; } // Driver code public static void main(String[] args) { int n = 5; System.out.println("The sum of divisors of" + " all numbers from 1 to " + n + " is: " + divisorSum(n)); n = 14; System.out.println("The sum of divisors of all" + " numbers from 1 to " + n + " is: " + divisorSum(n)); } } // This code is contributed by divyeshrabadiya07
Python3
# Python program to calculate # sum of divisors of numbers # from 1 to N in O(sqrt(N)) # complexity mod = 1000000007; # Function to calculate x^y using Modular exponentiation Refer to # https:#www.geeksforgeeks.org/ modular-exponentiation-power-in- # modular-arithmetic/ def power(x, y, p): # re x^y if p not specified # else (x^y)%p res = 1; x = x % p; while (y > 0): if ((y & 1) != 0): res = (res * x) % p; y = y >> 1; x = (x * x) % p; return (res + p) % p; # Function to find modular # inverse of a under modulo m # Assumption: m is prime def modinv(x): return power(x, mod - 2, mod); # Function to calculate sum # from 1 to n def sum(n): # sum 1 to n = (n*(n+1))/2 retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval; def divisorSum(n): l = 1; ans = 0; while (l <= n): k = n // l; r = n // k; k %= mod; # For i=l to i=r, # floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; # Since values can be very # large we need to take mod # at every step ans %= mod; l = r + 1; ans = ans % mod; return ans; # Driver code if __name__ == '__main__': n = 5; print("The sum of divisors of all numbers from 1 to " , n , " is: " ,int( divisorSum(n))); n = 14; print("The sum of divisors of all numbers from 1 to ", n ," is: " , int(divisorSum(n))); # This code contributed by aashish1995 Write
C#
// C# program to calculate // sum of divisors of numbers // from 1 to N in O(sqrt(N)) // complexity using System; class GFG{ static int mod = 1000000007; /* Function to calculate x^y using Modular exponentiation Refer to https://www.geeksforgeeks.org/ modular-exponentiation-power-in- modular-arithmetic/ */ static long power(long x, long y, long p) { // re x^y if p not specified // else (x^y)%p long res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p; } // Function to find modular // inverse of a under modulo m // Assumption: m is prime static long modinv(long x) { return power(x, mod - 2, mod); } // Function to calculate sum // from 1 to n static long sum(long n) { // sum 1 to n = (n*(n+1))/2 long retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval; } static long divisorSum(long n) { long l = 1; long ans = 0; while (l <= n) { long k = n / l; long r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans; } // Driver code static void Main() { int n = 5; Console.WriteLine("The sum of divisors of" + " all numbers from 1 to " + n + " is: " + divisorSum(n)); n = 14; Console.WriteLine("The sum of divisors of all" + " numbers from 1 to " + n + " is: " + divisorSum(n)); } } // This code is contributed by divyesh072019
Javascript
<script> // Javascript program to calculate // sum of divisors of numbers // from 1 to N in O(sqrt(N)) // complexity var mod = 10007; /* Function to calculate x^y using Modular exponentiation Refer to https://www.geeksforgeeks.org/ modular-exponentiation-power-in- modular-arithmetic/ */ function power(x, y, p) { // re x^y if p not specified // else (x^y)%p var res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p; } // Function to find modular // inverse of a under modulo m // Assumption: m is prime function modinv(x) { return power(x, mod - 2, mod); } // Function to calculate sum // from 1 to n function sum(n) { // sum 1 to n = (n*(n+1))/2 var retval = Math.floor((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval; } function divisorSum(n) { var l = 1; var ans = 0; while (l <= n) { var k = n / l; var r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += Math.floor((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans; } // Driver code var n = 5; document.write("The sum of divisors of" + " all numbers from 1 to " + n + " is: " + divisorSum(n) +"<br>"); n = 14; document.write("The sum of divisors of all" + " numbers from 1 to " + n + " is: " + divisorSum(n)); // This code is contributed by shivanisinghss2110 </script>
Producción:
The sum of divisors of all numbers from 1 to 5 is: 21 The sum of divisors of all numbers from 1 to 14 is: 165
Complejidad del tiempo: O(sqrt(N))
Espacio auxiliar: O(1)
Otro enfoque sqrt(n):
Dondequiera que se use división en el siguiente artículo, significa división de enteros.
Comencemos con un ejemplo, supongamos que n = 20, ahora veamos cómo cada número del 1 al 20 aparece como el factor de algún otro número.
1 : 1 * 1, 1 * 2, 1 * 3, 1 * 4..., 1 * (20 / 1) 2 : 2 * 1, 2 * 2, 2 * 3, 2 * 4,..., 2 * (20 / 2) 3 : 3 * 1, 3 * 2, 3 * 3, 3 * 4...., 3 * (20 / 3)
nuestro objetivo es sumar cada número cada vez que aparece como el factor de algún otro número. Por ejemplo 3 aparece como el factor de (3 * 1), (3 * 2), (3 * 3)…, (3 * (20 / 3)). Ahora empecemos desde 1 y sumamos 1 a nuestra suma cada vez que aparezca y también sumaremos todos los números que salieron con 1, haremos lo mismo con 2 y cuando lleguemos a 3 ya habremos agregado 3 a nuestra suma cuando aparecía con 1 y 2 ahora solo sumaremos 3 cuando aparezca con números mayores a 2 es decir 3, 4, 5, 6 también sumaremos los números que aparecían con 3 así que sumaremos 4, 5 y 6 también (observe que aquí no sumaremos 3 dos veces debido a 3 * 3). Del mismo modo, cuando llegamos a 4, ya hemos agregado 4 cuando apareció con 1, 2 y 3, por lo que lo agregaremos solo cuando aparezca con números >= y sumaremos los números que aparecen con 4.
Finalmente, podemos decir que cuando estamos en un número i, ya hemos procesado los números del 1 al i – 1 y, por lo tanto, hemos agregado i cada vez que aparece con los números 1 a i – 1, por lo que esta vez solo necesitamos agregar i cada vez que aparece con números >= i también hay que sumar todos los números que aparecen junto con i y son > i.
Por lo tanto, para cada número i queremos agregar los siguientes términos a nuestra suma
t1 : (add i each time it appears with numbers >= itself) -> i * (num / i - (i - 1)) (recall i will appear with numbers 1 to num / i and we have already added i each time it appeared with a numbers less than itself) t2 : (add numbers that appear with i) -> (i + 1) + (i + 2) ... + (num / i) (numbers 1 to num / i will appear with i but we have already processed numbers 1 to i - 1 and added them when they appeared with i so now we only have to add the numbers that appear with i and are greater than i, here we will not add i itself because when i appears with itself it should be added only once and we have added it once in t1) we need to calculate t2 in O(1) time, here's how to do that t2 = (i + 1) + (i + 2) + (i + 3) + ... + (num / i) add and subtract 1 + 2 + 3 ... + i => t2 = 1 + 2 + 3 + ... + i + (i + 1) + (i + 2) + ... + (num / i) - (1 + 2 + 3 + ... + i) => t2 = (1 + 2 + 3 + .. + (num / i)) - (1 + 2 + 3 .. + i) => t2 = ((num / i) * (num / i + 1)) / 2 - (i * (i + 1)) / 2
Finalmente, veamos los números que son mayores que sqrt(num). Estos números solo aparecerán con números menores que sqrt(num). Digamos que x es un número mayor que sqrt(num)
we have, x > sqrt(num) multiply sqrt(num) on both sides => x * sqrt(num) > sqrt(num) * sqrt(num) => x * sqrt(num) > num
queremos agregar x cada vez que aparece, de la prueba anterior vemos que x multiplicado por la raíz de num en sí mismo es mayor que num, por lo tanto, x solo aparecerá con números menores que la raíz de num, por lo que si procesamos todos los números de 1 a sqrt (num) sumaremos cada vez que aparezca x. Por ejemplo, tome n = 100, ahora considere 11, 11 * 10 > 100, por lo que 11 aparece solo con 1 a 9, es decir, como un factor de 11, 22, 33,…, 99. Lo mismo es cierto para el resto de los números que son mayores que 10. solo aparecerán con números menores a 10 y por lo tanto solo necesitamos procesar los números del 1 al 10 para sumar los números mayores a 10 para n = 100.
Finalmente, nuestra solución es esta
for each i in 1 to sqrt(num) //no need to visit numbers greater than the root add t1 and t2 to the sum
a continuación se muestra el código c ++
C++
#include <bits/stdc++.h> using namespace std; long long sum_all_divisors(long long num) { long long sum = 0; for (long long i = 1; i <= sqrt(num); i++) { long long t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself long long t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum; } int main() { int n; long long sum = sum_all_divisors(n); cout << sum << '\n'; return 0; }
Java
import java.io.*; class GFG { public static int sum_all_divisors(int num) { int sum = 0; for (int i = 1; i <= Math.sqrt(num); i++) { int t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself int t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum; } // Driver code public static void main (String[] args) { int n = 1; int sum = sum_all_divisors(n); System.out.println(sum); } } // This code is contributed by shivanisinghss2110
Python3
import math def sum_all_divisors(num): sum = 0; for i in range(1,math.floor(math.sqrt(num))+1): t1 = i * (num / i - i + 1) # adding i every time it appears with numbers greater than or equal to itself t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2) # adding numbers that appear with i and are greater than i sum += t1 + t2; return sum; n = 1 sum = sum_all_divisors(n) print(sum) # This code is contributed by shivanisinghss2110
C#
using System; class GFG { public static int sum_all_divisors(int num) { int sum = 0; for (int i = 1; i <= Math.Sqrt(num); i++) { int t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself int t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum; } // Driver code public static void Main (String[] args) { int n = 1; int sum = sum_all_divisors(n); Console.Write(sum); } } // This code is contributed by shivanisinghss2110
Javascript
<script> function sum_all_divisors(num) { var sum = 0; for (var i = 1; i <= Math.sqrt(num); i++) { var t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself var t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum; } var n; var sum = sum_all_divisors(n); document.write( sum ); // This code is contributed by shivanisinghss2110 </script>
Complejidad del tiempo: O(sqrt(N))
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por Shubham Bansal 13 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA