给定两个整数N和K ,其中N,K> 0 ,任务是找到对数(a,b) ,其中1≤a,b≤N,这样a%b = K。
例子:
Input: N = 4, K = 2
Output: 2
Only valid pairs are (2, 3) and (2, 4).
Input: N = 11, K = 5
Output: 7
天真的方法:从1到n运行两个循环,并计算所有对(i,j) ,其中i%j = K。这种方法的时间复杂度将是O(n 2 ) 。
高效的方法:最初的总计数= N – K,因为该范围内所有大于K的数字都将除以K作为余数。此后,对于所有i> K ,都有(N-K)/ i个正好数字,除以i后,余数将为K。
以下是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count
// of required pairs
int CountAllPairs(int N, int K)
{
int count = 0;
if (N > K) {
// Initial count
count = N - K;
for (int i = K + 1; i <= N; i++)
count = count + ((N - K) / i);
}
return count;
}
// Driver code
int main()
{
int N = 11, K = 5;
cout << CountAllPairs(N, K);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG {
// Function to return the count
// of required pairs
static int CountAllPairs(int N, int K)
{
int count = 0;
if (N > K) {
// Initial count
count = N - K;
for (int i = K + 1; i <= N; i++)
count = count + ((N - K) / i);
}
return count;
}
// Driver code
public static void main(String[] args)
{
int N = 11, K = 5;
System.out.println(CountAllPairs(N, K));
}
}
Python3
# Python3 implementation of the approach
import math
# Function to return the count
# of required pairs
def CountAllPairs(N, K):
count = 0
if( N > K):
# Initial count
count = N - K
for i in range(K + 1, N + 1):
count = count + ((N - K) // i)
return count
# Driver code
N = 11
K = 5
print(CountAllPairs(N, K))
C#
// C# implementation of the approach
using System;
class GFG {
// Function to return the count
// of required pairs
static int CountAllPairs(int N, int K)
{
int count = 0;
if (N > K) {
// Initial count
count = N - K;
for (int i = K + 1; i <= N; i++)
count = count + ((N - K) / i);
}
return count;
}
// Driver code
public static void Main()
{
int N = 11, K = 5;
Console.WriteLine(CountAllPairs(N, K));
}
}
PHP
$K){
// Initial count
$count = $N - $K;
for($i = $K+1; $i <= $N ; $i++)
{
$x = ((($N - $K) / $i));
$count = $count + (int)($x);
}
}
return $count;
}
// Driver code
$N = 11;
$K = 5;
echo(CountAllPairs($N, $K));
?>
输出:
7