Sum of all numbers up to N that are co | Function to return gcd of a and b ; Base Case ; Recursive GCD ; Function to calculate the sum of all numbers till N that are coprime with N ; Stores the resultant sum ; Iterate over [ 1 , N ] ; If gcd is 1 ; Update sum ; Return the final sum ; Given N ; Function Call
function gcd ( a , b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } function findSum ( N ) { var sum = 0 ; for ( var i = 1 ; i < N ; i ++ ) { if ( gcd ( i , N ) == 1 ) { sum += i ; } } return sum ; } var N = 5 ; document . write ( findSum ( N ) ) ;