Home > Backend Development > C++ > body text

C/C++ program to find remainder of array product divided by n

WBOY
Release: 2023-08-29 18:37:02
forward
636 people have browsed it

C/C++ 程序以找到数组乘积除以 n 的余数

Array multiplication, we will find the product of all the elements of the given array. Then according to the problem, we will divide the product by the number n. Let us take an example −

Input: arr[] = { 12, 35, 69, 74, 165, 54};
      N = 47
Output: 14
Copy after login

Explanation

The array is as follows {12, 35, 69, 74, 165, 54}, so the product is (12 * 35 * 69 * 74 * 165 * 54) = 19107673200. Now if we want to get the remainder after dividing by 47, the result is 14.

First multiply all the numbers, then take % of n and find the remainder. But in this method, if the number reaches the maximum value of 2^64, it will give wrong answer.

Example

#include <stdio.h>
int main() {
   int arr[] = { 12, 35, 69, 74, 165, 54};
   int len = 6;
   int n = 47 ;
   int mul = 1;
   for (int i = 0; i < len; i++)
      mul = (mul * (arr[i] % n)) % n;
   printf("the remainder is %d", (mul%n));
   return 0;
}
Copy after login

Output

the remainder is 14
Copy after login

The above is the detailed content of C/C++ program to find remainder of array product divided by n. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template