给定一个数组arr []和一个正整数P ,其中P是素数,并且array的所有元素都不能被P整除。求出提高到幂P – 1的数组所有元素的总和,即arr [0] P – 1 + arr [1] P – 1 +…+ arr [n – 1] P – 1并以模P打印结果。
例子:
Input: arr[] = {2, 5}, P = 3
Output: 2
22 + 52 = 29 and 29 % 3 = 2
Input: arr[] = {5, 6, 8}, P = 7
Output: 3
方法:这个问题是费马小定理a (P-1) = 1(mod p)的直接应用,其中a不能被P整除。由于数组arr []的所有元素都不能被P整除,因此每个元素arr [i]在给定的操作下将得到值1 。
因此,我们的答案将是1 +1 +…(最大n(数组的大小))= n 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
#include
using namespace std;
// Function to return the required sum
int getSum(vector arr, int p)
{
return arr.size();
}
// Driver code
int main()
{
vector arr = { 5, 6, 8 };
int p = 7;
cout << getSum(arr, p) << endl;
return 0;
}
// This code is contributed by Rituraj Jain
Java
// Java implementation of the approach
public class GFG {
// Function to return the required sum
public static int getSum(int arr[], int p)
{
return arr.length;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 5, 6, 8 };
int p = 7;
System.out.print(getSum(arr, p));
}
}
Python3
# Python3 implementation of the approach
# Function to return the required sum
def getSum(arr, p) :
return len(arr)
# Driver code
if __name__ == "__main__" :
arr = [5, 6, 8]
p = 7
print(getSum(arr, p))
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
public class GFG{
// Function to return the required sum
public static int getSum(int []arr, int p)
{
return arr.Length;
}
// Driver code
static public void Main (){
int []arr = { 5, 6, 8 };
int p = 7;
Console.WriteLine(getSum(arr, p));
}
//This Code is contributed by akt_mit
}
PHP
输出:
3