给定整数N及其除数之和。任务是找到N的除数的逆之和。
例子:
Input: N = 6, Sum = 12
Output: 2.00
Divisors of N are {1, 2, 3, 6}
Sum of inverse of divisors is equal to (1/1 + 1/2 + 1/3 + 1/6) = 2.0
Input: N = 9, Sum = 13
Output: 1.44
天真的方法:计算给定整数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≤K , N / 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)