Find the permutation of first N natural numbers such that sum of i % Pi is maximum possible
Last Updated :
09 Dec, 2022
Given a number N. The task is to find the permutation P of first N natural numbers such that sum of i % Pi is maximum possible. The task is to find the maximum possible sum not it’s permutation.
Examples:
Input: N = 5
Output: 10
Possible permutation is 2 3 4 5 1.
Modulus values will be {1, 2, 3, 4, 0}.
1 + 2 + 3 + 4 + 0 = 10
Input: N = 8
Output: 28
Approach: Maximum possible sum is (N * (N – 1)) / 2 and it is formed by the permutation 2, 3, 4, 5, ….. N, 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int Max_Sum( int n)
{
return (n * (n - 1)) / 2;
}
int main()
{
int n = 8;
cout << Max_Sum(n);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static int Max_Sum( int n)
{
return (n * (n - 1 )) / 2 ;
}
public static void main (String[] args)
{
int n = 8 ;
System.out.println(Max_Sum(n));
}
}
|
Python3
def Max_Sum(n) :
return (n * (n - 1 )) / / 2 ;
if __name__ = = "__main__" :
n = 8 ;
print (Max_Sum(n));
|
C#
using System;
class GFG
{
static int Max_Sum( int n)
{
return (n * (n - 1)) / 2;
}
public static void Main (String[] args)
{
int n = 8;
Console.WriteLine(Max_Sum(n));
}
}
|
Javascript
<script>
function Max_Sum(n)
{
return parseInt((n * (n - 1)) / 2);
}
let n = 8;
document.write(Max_Sum(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...