求数组乘法除以 n 的余数
给定多个数字和一个数字 n,任务是打印所有数字除以 n 后的余数。
例子:
Input : arr[] = {100, 10, 5, 25, 35, 14},
n = 11
Output : 9
100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9
Input : arr[] = {100, 10},
n = 5
Output : 0
100 x 10 = 1000 % 5 = 0
天真的方法:首先将所有数字相乘,然后将 % 乘以 n,然后找到余数,但在这种方法中,如果数字最大为 2^64,那么它会给出错误的答案。
避免溢出的方法:首先取一个余数或单个数字,如 arr[i] % n。然后将余数乘以当前结果。乘法后,再次取余数以避免溢出。这是因为模算术的分布特性。 ( a * b) % c = ( ( a % c ) * ( b % c ) ) % c
C++
// C++ program to find
// remainder when all
// array elements are
// multiplied.
#include
using namespace std;
// Find remainder of arr[0] * arr[1] *
// .. * arr[n-1]
int findremainder(int arr[], int len, int n)
{
int mul = 1;
// find the individual remainder
// and multiple with mul.
for (int i = 0; i < len; i++)
mul = (mul * (arr[i] % n)) % n;
return mul % n;
}
// Driver code
int main()
{
int arr[] = { 100, 10, 5, 25, 35, 14 };
int len = sizeof(arr) / sizeof(arr[0]);
int n = 11;
// print the remainder of after
// multiple all the numbers
cout << findremainder(arr, len, n);
}
Java
// Java program to find
// remainder when all
// array elements are
// multiplied.
import java.util.*;
import java.lang.*;
public class GfG{
// Find remainder of arr[0] * arr[1] *
// .. * arr[n-1]
public static int findremainder(int arr[],
int len, int n)
{
int mul = 1;
// find the individual remainder
// and multiple with mul.
for (int i = 0; i < len; i++)
mul = (mul * (arr[i] % n)) % n;
return mul % n;
}
// Driver function
public static void main(String argc[])
{
int[] arr = new int []{ 100, 10, 5,
25, 35, 14 };
int len = 6;
int n = 11;
// print the remainder of after
// multiple all the numbers
System.out.println(findremainder(arr, len, n));
}
}
/* This code is contributed by Sagar Shukla */
Python3
# Python3 program to
# find remainder when
# all array elements
# are multiplied.
# Find remainder of arr[0] * arr[1]
# * .. * arr[n-1]
def findremainder(arr, lens, n):
mul = 1
# find the individual
# remainder and
# multiple with mul.
for i in range(lens):
mul = (mul * (arr[i] % n)) % n
return mul % n
# Driven code
arr = [ 100, 10, 5, 25, 35, 14 ]
lens = len(arr)
n = 11
# print the remainder
# of after multiple
# all the numbers
print( findremainder(arr, lens, n))
# This code is contributed by "rishabh_jain".
C#
// C# program to find
// remainder when all
// array elements are
// multiplied.
using System;
public class GfG{
// Find remainder of arr[0] * arr[1] *
// .. * arr[n-1]
public static int findremainder(int []arr,
int len, int n)
{
int mul = 1;
// find the individual remainder
// and multiple with mul.
for (int i = 0; i < len; i++)
mul = (mul * (arr[i] % n)) % n;
return mul % n;
}
// Driver function
public static void Main()
{
int[] arr = new int []{ 100, 10, 5,
25, 35, 14 };
int len = 6;
int n = 11;
// print the remainder of after
// multiple all the numbers
Console.WriteLine(findremainder(arr, len, n));
}
}
/* This code is contributed by vt_m */
PHP
Javascript
输出:
9
时间复杂度: O(len),其中 len 是给定数组的大小
辅助空间: O(1)