给定一个素数N ,任务是找到最接近的小于N 的数,使得模 N 下的数的模乘逆等于该数本身。
例子:
Input: N = 7
Output: 6
Explanation:
Modulo multiplicative inverse of all possible natural numbers from 1 to less than N are:
Modulo multiplicative inverse of 1 under modulo N(=7) is 1.
Modulo multiplicative inverse of 2 under modulo N(=7) is 4.
Modulo multiplicative inverse of 3 under modulo N(=7) is 5.
Modulo multiplicative inverse of 4 under modulo N(=7) is 2.
Modulo multiplicative inverse of 5 under modulo N(=7) is 3.
Modulo multiplicative inverse of 6 under modulo N(=7) is 6.
Therefore, the nearest smaller number to N(= 7) having modulo inverse equal to the number itself is 6.
Input: N = 11
Output: 10
朴素的方法:解决这个问题的最简单的方法是遍历从 1 到 N 的所有自然数,并找到最大的数,使得模 N 下的数的模乘法逆等于该数本身。
时间复杂度: O(N * log N)
辅助空间: O(1)
高效的方法:为了优化上述方法,该想法基于以下观察:
The nearest smaller number to N having modulo multiplicative inverse equal to the number itself is (N – 1).
Mathematical proof:
If X and Y are two numbers such that (X * Y) % N = 1 mod(N), then Y is modulo inverse of X.
Put X = N – 1 then
=>((N – 1) * Y) % N = 1 mod(N)
=>(N × Y) % N – Y % N = 1 mod(N)
=> Y = N – 1
Therefore, for X = N – 1 the value of Y is equal to X.
因此,要解决问题,只需打印N – 1作为所需答案。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to find the nearest
// smaller number satisfying
// the condition
int clstNum(int N)
{
return (N - 1);
}
// Driver Code
int main()
{
int N = 11;
cout << clstNum(N);
}
Java
// Java program to implement
// the above approach
import java.io.*;
class GFG{
// Function to find the nearest
// smaller number satisfying
// the condition
static int clstNum(int N){ return (N - 1); }
// Driver Code
public static void main(String[] args)
{
int N = 11;
System.out.println(clstNum(N));
}
}
// This code is contributed by akhilsaini
Python3
# Python3 program to implement
# the above approach
# Function to find the nearest
# smaller number satisfying
# the condition
def clstNum(N):
return (N - 1)
# Driver Code
if __name__ == '__main__':
N = 11
print(clstNum(N))
# This code is contributed by akhilsaini
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to find the nearest
// smaller number satisfying
// the condition
static int clstNum(int N){ return (N - 1); }
// Driver Code
public static void Main()
{
int N = 11;
Console.Write(clstNum(N));
}
}
// This code is contributed by akhilsaini
Javascript
10
时间复杂度: O(1)
辅助空间: O(1)