Count of pairs from first N natural numbers with remainder at least K | Function to count the number of pairs ( a , b ) such that a % b is at least K ; Base Case ; Stores resultant count of pairs ; Iterate over the range [ K + 1 , N ] ; Find the cycled elements ; Find the remaining elements ; Return the resultant possible count of pairs ; Driver Code
function countTotalPairs ( N , K ) { if ( K == 0 ) { return N * N ; } let ans = 0 ; for ( let b = K + 1 ; b <= N ; b ++ ) { ans += Math . floor ( ( N / b ) * ( b - K ) ) ; ans += Math . max ( N % b - K + 1 , 0 ) ; } return ans ; } let N = 5 , K = 2 ; document . write ( countTotalPairs ( N , K ) ) ;