📜  当给出除数之和和个数时,求除数的反数之和

📅  最后修改于: 2021-04-23 19:07:19             🧑  作者: Mango

给定整数N及其除数之和。任务是找到N的除数的逆之和。

例子:

天真的方法:计算给定整数N的所有除数。然后计算所计算的除数的逆之和。当N的值较大时,此方法将给TLE。
时间复杂度: O(sqrt(N))

高效的方法:N个数为K的除数为d 1 ,d 2 ,…,d K。假设d 1 + d 2 +…+ d K =总和
任务是计算(1 / d 1 )+(1 / d 2 )+…+(1 / d K )
将上述方程式乘以N并除以。等式变为[(N / d 1 )+(N / d 2 )+…+(N / d K )] / N

现在很容易看出,对于所有1≤i≤KN / d i代表N的另一个约数。分子等于除数之和。因此,除数的逆之和等于Sum / N。

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
  
// Function to return the
// sum of inverse of divisors
double SumofInverseDivisors(int N, int Sum)
{
  
    // Calculating the answer
    double ans = (double)(Sum)*1.0 / (double)(N);
  
    // Return the answer
    return ans;
}
  
// Driver code
int main()
{
    int N = 9;
  
    int Sum = 13;
  
    // Function call
    cout << setprecision(2) << fixed
         << SumofInverseDivisors(N, Sum);
  
    return 0;
}


Java
// Java implementation of above approach
import java.math.*;
import java.io.*;
  
class GFG 
{
      
// Function to return the
// sum of inverse of divisors
static double SumofInverseDivisors(int N, int Sum)
{
  
    // Calculating the answer
    double ans = (double)(Sum)*1.0 / (double)(N);
  
    // Return the answer
    return ans;
}
  
// Driver code
public static void main (String[] args) 
{
  
    int N = 9;
    int Sum = 13;
  
    // Function call
    System.out.println (SumofInverseDivisors(N, Sum));
}
}
  
// This code is contributed by jit_t.


Python
# Python implementation of above approach
  
# Function to return the
# sum of inverse of divisors
def SumofInverseDivisors( N, Sum):
  
    # Calculating the answer
    ans = float(Sum)*1.0 /float(N);
  
    # Return the answer
    return round(ans,2);
  
  
# Driver code
N = 9;
Sum = 13;
print SumofInverseDivisors(N, Sum);
  
# This code is contributed by CrazyPro


C#
// C# implementation of above approach
using System;
  
class GFG
{
          
// Function to return the
// sum of inverse of divisors
static double SumofInverseDivisors(int N, int Sum)
{
  
    // Calculating the answer
    double ans = (double)(Sum)*1.0 / (double)(N);
  
    // Return the answer
    return ans;
}
  
// Driver code
static public void Main ()
{
      
    int N = 9;
    int Sum = 13;
  
    // Function call
    Console.Write(SumofInverseDivisors(N, Sum));
}
}
  
// This code is contributed by ajit


输出:
1.44

时间复杂度: O(1)