📜  计算从1到N的数字对,其乘积可被其和除

📅  最后修改于: 2021-04-23 15:54:42             🧑  作者: Mango

给定一个数字N   。任务是对对(x,y)进行计数,以使x * y可被(x + y)整除,并且条件1 <= x 成立。
例子

Input : N = 6
Output : 1
Explanation: The only pair is (3, 6) which satisfies
all of the given condition, 3<6 and 18%9=0.

Input : N = 15
Output : 4

基本方法是使用两个循环进行迭代,仔细地保持给定条件1 <= x 并生成所有可能的有效对,并对这些对的值乘以可除的计数。
下面是上述方法的实现:

C++
// C++ program to count pairs of numbers
// from 1 to N with Product divisible
// by their Sum
 
#include 
using namespace std;
 
// Function to count pairs
int countPairs(int n)
{
    // variable to store count
    int count = 0;
 
    // Generate all possible pairs such that
    // 1 <= x < y < n
    for (int x = 1; x < n; x++) {
        for (int y = x + 1; y <= n; y++) {
            if ((y * x) % (y + x) == 0)
                count++;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    int n = 15;
 
    cout << countPairs(n);
 
    return 0;
}


Java
// Java program to count pairs of numbers
// from 1 to N with Product divisible
// by their Sum
 
import java.io.*;
 
class GFG {
  
 
 
// Function to count pairs
static int countPairs(int n)
{
    // variable to store count
    int count = 0;
 
    // Generate all possible pairs such that
    // 1 <= x < y < n
    for (int x = 1; x < n; x++) {
        for (int y = x + 1; y <= n; y++) {
            if ((y * x) % (y + x) == 0)
                count++;
        }
    }
 
    return count;
}
 
// Driver code
 
    public static void main (String[] args) {
            int n = 15;
 
    System.out.println(countPairs(n));
    }
}
// This code is contributed by anuj_67..


Python3
# Python 3 program to count pairs of numbers
# from 1 to N with Product divisible
# by their Sum
 
# Function to count pairs
def countPairs(n):
     
    # variable to store count
    count = 0
     
    # Generate all possible pairs such that
    # 1 <= x < y < n
    for x in range(1, n):
        for y in range(x + 1, n + 1):
            if ((y * x) % (y + x) == 0):
                count += 1
 
    return count
 
# Driver code
n = 15
print(countPairs(n))
 
# This code is contributed
# by PrinciRaj1992


C#
// C# program to count pairs of numbers
// from 1 to N with Product divisible
// by their Sum
using System;
 
class GFG
{
 
// Function to count pairs
static int countPairs(int n)
{
    // variable to store count
    int count = 0;
 
    // Generate all possible pairs
    // such that 1 <= x < y < n
    for (int x = 1; x < n; x++)
    {
        for (int y = x + 1; y <= n; y++)
        {
            if ((y * x) % (y + x) == 0)
                count++;
        }
    }
 
    return count;
}
 
// Driver code
public static void Main ()
{
    int n = 15;
 
    Console.WriteLine(countPairs(n));
}
}
 
// This code is contributed by anuj_67


PHP


Javascript


输出:
4

时间复杂度: O(N 2 )