Given an integer N and the sum of its divisors. The task is to find the sum of the inverse of the divisors of N.
Examples:
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
Naive Approach: Calculate all the divisors of the given integer N. Then calculate the sum of the inverse of the calculated divisors. This approach would give TLE when the value of N is large.
Time Complexity: O(sqrt(N))
Efficient Approach: Let the number N has K divisors say d1, d2, …, dK. It is given that d1 + d2 + … + dK = Sum
The task is to calculate (1 / d1) + (1 / d2) + … + (1 / dK).
Multiply and divide the above equation by N. The equation becomes [(N / d1) + (N / d2) + … + (N / dK)] / N
Now it is easy to see that N / di would represent another divisor of N for all 1 ? i ? K. The numerator is equal to the sum of the divisors. Hence, sum of inverse of the divisors is equal to Sum / N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
double SumofInverseDivisors( int N, int Sum)
{
double ans = ( double )(Sum)*1.0 / ( double )(N);
return ans;
}
int main()
{
int N = 9;
int Sum = 13;
cout << setprecision(2) << fixed
<< SumofInverseDivisors(N, Sum);
return 0;
}
|
Java
import java.math.*;
import java.io.*;
class GFG
{
static double SumofInverseDivisors( int N, int Sum)
{
double ans = ( double )(Sum)* 1.0 / ( double )(N);
return ans;
}
public static void main (String[] args)
{
int N = 9 ;
int Sum = 13 ;
System.out.println (SumofInverseDivisors(N, Sum));
}
}
|
Python
def SumofInverseDivisors( N, Sum ):
ans = float ( Sum ) * 1.0 / float (N);
return round (ans, 2 );
if __name__ = = "__main__" :
N = 9 ;
Sum = 13 ;
print (SumofInverseDivisors(N, Sum ))
|
C#
using System;
class GFG
{
static double SumofInverseDivisors( int N, int Sum)
{
double ans = ( double )(Sum)*1.0 / ( double )(N);
return ans;
}
static public void Main ()
{
int N = 9;
int Sum = 13;
Console.Write(SumofInverseDivisors(N, Sum));
}
}
|
Javascript
<script>
function SumofInverseDivisors(N, Sum)
{
let ans = (Sum)*1.0 / (N);
return ans;
}
let N = 9;
let Sum = 13;
document.write(SumofInverseDivisors(N, Sum).toFixed(2));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
12 Apr, 2023
Like Article
Save Article