zoukankan      html  css  js  c++  java
  • ZOJ 3609 求逆元

    Modular Inverse

    Time Limit: 2 Seconds      Memory Limit: 65536 KB

    The modular modular multiplicative inverse of an integer a modulo m is an integer x such that a-1x (mod m). This is equivalent to ax≡1 (mod m).

    Input

    There are multiple test cases. The first line of input is an integer T ≈ 2000 indicating the number of test cases.

    Each test case contains two integers 0 < a ≤ 1000 and 0 < m ≤ 1000.

    Output

    For each test case, output the smallest positive x. If such x doesn't exist, output "Not Exist".

    Sample Input

    3
    3 11
    4 12
    5 13
    

    Sample Output

    4
    Not Exist
    8

    简单题,求逆元。 最小的x>0,满足ax==1 (mod m)

    am都很小,不超过1000。所以可以暴力枚举x1开始枚举,

    因为是对m取模的,所枚举x1m即可。另外m有可能等于1

    所以直接判断a*x%m==1会错。改用(a*x-1)%m==0即可,

    另外也可以不用乘法,从(a-1)开始每次加a就可以了,但这都无所谓。

    还有,循环终止应该到m,而不是(m-1),本来到m的话ax==0 (mod m)肯定不对,

    但还是因为有m=1的问题:0==1 (mod 1) 否则ax==1会无解错掉。

     1 #include<stdio.h> 
     2 #include<string.h>
     3 #include<algorithm> 
     4 using namespace std; 
     5 int gcd(int x,int y){
     6     int z;
     7     while(y){
     8         z=y;
     9         y=x%y;
    10         x=z;
    11     }
    12     return x;
    13 }
    14 int main(){
    15     int t,a,m,i,ans;
    16     scanf("%d",&t);
    17     while(t--){
    18         scanf("%d%d",&a,&m);
    19         ans=gcd(a,m);
    20         if(ans>1)
    21             printf("Not Exist
    ");
    22         else{
    23             i=1;
    24             while((a*i-1)%m!=0) //这一步判断很重要
    25                 i++;
    26             printf("%d
    ",i);
    27         }
    28     }
    29     return 0;
    30 }
  • 相关阅读:
    蓝绿发布、灰度发布和滚动发布
    centos网卡配置修改
    服务器安装centos8提示显示器不支持输出的分辨率
    Linux软件包管理
    Redis (error) NOAUTH Authentication required.解决方法
    mysql5.7.35数据库迁移
    MySQL5.7的参数优化
    mysql 安装完以后没有mysql服务
    Promise结合setTimeout--promise练习题(2)
    基础题--promise练习题(1)
  • 原文地址:https://www.cnblogs.com/wushuaiyi/p/3641854.html
Copyright © 2011-2022 走看看