到目前为止,我已经解决了euclid,lCM,extGCD和coprime。我如何解决模块化反向(minv)?我认为"假设n是互质"令我困惑。
void
答案 0 :(得分:3)
您可以使用extGCD
功能执行此操作。
如果 a 和 m 是共同素数,那么请使用extGCD
函数来解决:
a*x + m*y = gcd a m = 1
这意味着 a * x = 1 mod m ,即 a 和 x 是乘法逆的mod m 。
答案 1 :(得分:2)
首先,@interface MyDataManager
@end
@implementation MyDataManager
+ (MyDataManager *)mainStore {
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (void)myMethod {
NSDictionary *args = @{...}
...
dispatch_async(dispatch_get_main_queue(), ^{
[self cleanupMethod:args];
});
}
- (void)cleanupMethod:(id)args {
...
}
@end
@interface MyViewController : UIViewController
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[MyDataManager sharedInstance] myMethod];
}
@end
和a
必须是互质的,否则反转不存在。这是因为找到n
modulo a
的倒数与求解同余相同:n
。
线性同余ax = 1 mod n
仅在ax = b mod n
时才有解。但在这种情况下,gcd(a, n) | b
意味着gcd(a, n) | 1
。
现在,为了找到逆,你使用Bezout身份,即存在gcd(a, n) = 1
和x
,以便:y
。您已在gcd(a, n) = a*x + n*y
函数中找到了此类值,因此您可以将extGCD
实现为:
minv
如果minv a n = a*x + n*y
(x, y, _) = extGCD a n
与Integer -> Integer -> Maybe Integer
不同,最好编写类型为Nothing
的函数并返回extGCD
:
1
另外:Z n 中的可逆元素的子群恰好是minv a n =
| g == 1 = Just $ a*x + n*y
| otherwise = Nothing
where
(x, y, g) = extGCD a n
s< 1>的集合。 a
互译n
。当n
为素数时,此子组与没有n
的Z n 重合,在这种情况下,Z n 是一个字段。