I have a value N which varies from
1 <= N <= 10^6
Say:
N = 5
I want to calculate sum
where :
sum = gcd(1,5) + gcd(2,5) + gcd(3,5) + gcd(4,5) + gcd(5,5)
I achieved this by writing these two functions :
function calculateSum($N){
$gcdSum = 0;
for($i = 1; $i <= $N; $i++){
$gcdSum += gcd($N,$i);
}
return $gcdSum;
}
function gcd($a, $b){
if($b == 0) {
return $a;
}
else {
return gcd($b, $a % $b);
}
}
I want to know what other better and faster ways of doing this exist and how to achieve them.