Maximum sum of distinct numbers such that LCM of these numbers is N
Given a positive number N. The task is to find the maximum sum of distinct numbers such that the LCM of all these numbers is equal to N.
Examples:
Input : 2
Output : 3
The distinct numbers you can have are
just 1 and 2 and their sum is equal to 3.
Input : 5
Output : 6
As the LCM of all the numbers is N. So all the numbers must be the divisors of N and all the numbers are distinct so answer must be the sum of all the divisors of N. To find all the divisors efficiently refer to article https://www.geeksforgeeks.org/find-all-divisors-of-a-natural-number-set-2/
Here are the steps to solve this problem :
- Find all the divisors of ‘n’ by iterating from 1 to the square root of the n.
- If i!= n/i, add n/i to max sum as well as each divisor i to max_sum.
- Return max_sum as the final result.
Below is the implementation of the above approach.
C++
#include<bits/stdc++.h>
using namespace std;
int maxSumLCM( int n)
{
int max_sum = 0;
for ( int i=1; i*i<=n; i++)
{
if (n%i == 0)
{
max_sum += i;
if (n/i != i)
max_sum += (n/i);
}
}
return max_sum;
}
int main()
{
int n = 2;
cout << maxSumLCM(n) << endl;
return 0;
}
|
Java
class MaxSum
{
static int maxSumLCM( int n)
{
int max_sum = 0 ;
for ( int i= 1 ; i*i<=n; i++)
{
if (n%i == 0 )
{
max_sum += i;
if (n/i != i)
max_sum += (n/i);
}
}
return max_sum;
}
public static void main (String[] args)
{
int n = 2 ;
System.out.println(maxSumLCM(n));
}
}
|
Python3
def maxSumLCM(n) :
max_sum = 0
i = 1
while (i * i< = n ):
if (n % i = = 0 ) :
max_sum = max_sum + i
if (n / / i ! = i) :
max_sum = max_sum + (n / / i)
i = i + 1
return max_sum
n = 2
print (maxSumLCM(n))
|
C#
using System;
class MaxSum
{
static int maxSumLCM( int n)
{
int max_sum = 0;
for ( int i = 1; i * i <= n; i++)
{
if (n % i == 0)
{
max_sum += i;
if (n / i != i)
max_sum += (n / i);
}
}
return max_sum;
}
public static void Main (String[] args)
{
int n = 2;
Console.Write(maxSumLCM(n));
}
}
|
PHP
<?php
function maxSumLCM( $n )
{
$max_sum = 0;
for ( $i = 1;
$i * $i <= $n ; $i ++)
{
if ( $n % $i == 0)
{
$max_sum += $i ;
if ( $n / $i != $i )
$max_sum += ( $n / $i );
}
}
return $max_sum ;
}
$n = 2;
echo MaxSumLCM( $n );
?>
|
Javascript
<script>
function maxSumLCM(n)
{
let max_sum = 0;
for (let i=1; i*i<=n; i++)
{
if (n%i == 0)
{
max_sum += i;
if (n/i != i)
max_sum += (n/i);
}
}
return max_sum;
}
let n = 2;
document.write(maxSumLCM(n) + "<br>" );
</script>
|
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
Last Updated :
08 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...