Sum of each element raised to (prime-1) % prime
Last Updated :
21 Dec, 2022
Given an array arr[] and a positive integer P where P is prime and none of the elements of array are divisible by P. Find sum of all the elements of the array raised to the power P – 1 i.e. arr[0]P – 1 + arr[1]P – 1 + … + arr[n – 1]P – 1 and print the result modulo P.
Examples:
Input: arr[] = {2, 5}, P = 3
Output: 2
22 + 52 = 29 and 29 % 3 = 2
Input: arr[] = {5, 6, 8}, P = 7
Output: 3
Approach: This problem is a direct application of Fermats’s Little Theorem, a(P-1) = 1 (mod p) where a is not divisible by P. Since, none of the elements of array arr[] are divisible by P, each element arr[i] will give the value 1 with the given operation.
Therefore, our answer will be 1 + 1 + … (upto n(size of array)) = n.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
int getSum(vector< int > arr, int p)
{
return arr.size();
}
int main()
{
vector< int > arr = { 5, 6, 8 };
int p = 7;
cout << getSum(arr, p) << endl;
return 0;
}
|
Java
public class GFG {
public static int getSum( int arr[], int p)
{
return arr.length;
}
public static void main(String[] args)
{
int arr[] = { 5 , 6 , 8 };
int p = 7 ;
System.out.print(getSum(arr, p));
}
}
|
Python3
def getSum(arr, p) :
return len (arr)
if __name__ = = "__main__" :
arr = [ 5 , 6 , 8 ]
p = 7
print (getSum(arr, p))
|
C#
using System;
public class GFG{
public static int getSum( int []arr, int p)
{
return arr.Length;
}
static public void Main (){
int []arr = { 5, 6, 8 };
int p = 7;
Console.WriteLine(getSum(arr, p));
}
}
|
PHP
<?php
function getSum( $arr , $p )
{
return count ( $arr );
}
$arr = array ( 5, 6, 8 );
$p = 7;
echo (getSum( $arr , $p ));
?>
|
Javascript
<script>
function getSum(arr, p)
{
return arr.length;
}
let arr = [ 5, 6, 8 ];
let p = 7;
document.write(getSum(arr, p));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...