I need to find the SUMMATION of Si * Ci (for i in range of 1 to n).
Following are the constraints:
1 ≤ n ≤ 10^6
1 ≤ si ≤ 10^6
1 ≤ ci ≤ 10^6
Here is my code.
<?php
for($i = 0; $i < $n; $i++){
$total += ($s[$i] * $c[$i]);
}
?>
However, the code runs out of time for high input values(upto 10 ^ 6).
How to add such huge numbers with proper optimisation techniques without exceeding the execution time.
You can increase the max execution time using set_time_limit
Read more here: http://php.net/manual/en/function.set-time-limit.php
set_time_limit — Limits the maximum execution time
bool set_time_limit ( int $seconds )
If you set it to zero it will run forever until the script finishes execution or it is interrupted manually. Place this at the top of your script to do that:
set_time_limit(0);
Update:
Use a language other than PHP.
There are few aspects you should take care:
These operations could take lots of time, so you have to change request time limit:
set_time_limit(0);
PHP offers some map/reduce functions for such operations. One is array_map()
and another is array_reduce()
function multiply($s, $c) {
return $s * $c;
}
function sum($carry, $item)
{
$carry += $item;
return $carry;
}
$result = array_reduce(array_map('multiply', $s, $c), 'sum');
Of couse you can use anonymous functions as callbacks.
Depending on you data you should take care of capacity/precision problems. In this case take a look at bcmath
extension and bcmul()
bcadd()
functions.