📌  相关文章
📜  满足给定方程的最小正整数 X

📅  最后修改于: 2021-09-06 05:51:28             🧑  作者: Mango

给定两个整数NK ,任务是找到满足等式的最小正整数X

例子:

方法:
这个想法是观察到,因为(X / K) * (X % K) = N ,因此, N将被p = X % K整除,它小于K 。因此,对于[1, K)范围内的所有i尝试 p 的所有值,其中:

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find out the smallest
// positive integer for the equation
int findMinSoln(int n, int k)
{
    // Stores the minimum
    int minSoln = INT_MAX;
 
    // Iterate till K
    for (int i = 1; i < k; i++) {
 
        // Check if n is divisible by i
        if (n % i == 0)
            minSoln
                = min(minSoln, (n / i) * k + i);
    }
 
    // Return the answer
    return minSoln;
}
 
// Driver Code
int main()
{
    int n = 4, k = 6;
    cout << findMinSoln(n, k);
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
  
// Function to find out the smallest
// positive integer for the equation
static int findMinSoln(int n, int k)
{
    // Stores the minimum
    int minSoln = Integer.MAX_VALUE;
  
    // Iterate till K
    for (int i = 1; i < k; i++)
    {
  
        // Check if n is divisible by i
        if (n % i == 0)
            minSoln = Math.min(minSoln, (n / i) * k + i);
    }
  
    // Return the answer
    return minSoln;
}
  
// Driver Code
public static void main(String[] args)
{
    int n = 4, k = 6;
    System.out.println(findMinSoln(n, k));
}
}
 
// This code is contributed by Ritik Bansal


Python3
# Python3 program to implement
# the above approach
import sys
 
# Function to find out the smallest
# positive integer for the equation
def findMinSoln(n, k):
     
    # Stores the minimum
    minSoln = sys.maxsize;
 
    # Iterate till K
    for i in range(1, k):
 
        # Check if n is divisible by i
        if (n % i == 0):
            minSoln = min(minSoln, (n // i) * k + i);
     
    # Return the answer
    return minSoln;
 
# Driver Code
if __name__ == '__main__':
     
    n = 4;
    k = 6;
     
    print(findMinSoln(n, k));
 
# This code is contributed by amal kumar choubey


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to find out the smallest
// positive integer for the equation
static int findMinSoln(int n, int k)
{
     
    // Stores the minimum
    int minSoln = int.MaxValue;
 
    // Iterate till K
    for (int i = 1; i < k; i++)
    {
 
        // Check if n is divisible by i
        if (n % i == 0)
            minSoln = Math.Min(minSoln,
                              (n / i) * k + i);
    }
 
    // Return the answer
    return minSoln;
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 4, k = 6;
     
    Console.WriteLine(findMinSoln(n, k));
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
10

时间复杂度: O(N)
辅助空间: O(1)