Php Program for Products of ranges in an array
Given an array A[] of size N. Solve Q queries. Find the product in the range [L, R] under modulo P ( P is Prime).Â
Examples:Â Â
Input : A[] = {1, 2, 3, 4, 5, 6}
L = 2, R = 5, P = 229
Output : 120
Input : A[] = {1, 2, 3, 4, 5, 6},
L = 2, R = 5, P = 113
Output : 7
Brute Force
For each of the queries, traverse each element in the range [L, R] and calculate the product under modulo P. This will answer each query in O(N). Â
PHP
<?php
function calculateProduct( $A , $L ,
$R , $P )
{
$L = $L - 1;
$R = $R - 1;
$ans = 1;
for ( $i = $L ; $i <= $R ; $i ++)
{
$ans = $ans * $A [ $i ];
$ans = $ans % $P ;
}
return $ans ;
}
$A = array ( 1, 2, 3, 4, 5, 6 );
$P = 229;
$L = 2; $R = 5;
echo calculateProduct( $A , $L , $R , $P ),"
" ;
$L = 1; $R = 3;
echo calculateProduct( $A , $L , $R , $P ),"
" ;
?>
|
Output :Â Â
120
6
Please refer complete article on Products of ranges in an array for more details!
Last Updated :
13 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...