【问题标题】:Calculating modulo inverse in java在java中计算模逆
【发布时间】:2021-01-15 04:36:35
【问题描述】:

我试图找出一种使用 java 计算模逆的方法,所以我编写了这个函数来做到这一点:

public static int privatekey(int primeprod, int e, int lambda)
{
    Random random = new Random();
    float d = 0;
    //extended euler's theorem is
    //d = (1 + x*lambda) / e
    //d is smaller than primeprod
    while(true)
    {
        int d = random.nextInt(200) + 1;
        System.out.println("seed: "+x);
        var = (1 + (x*lambda)) / e;
        System.out.println("var: "+d);
        if(isInteger(d) && d < primeprod)
        {
            break;
        }
    }
    int finalvar = (int)d;
    return finalvar;
}

我觉得它出了问题,所以我将上面使用的欧几里得定理扩展反转如下

1 + x.lambda
------------- = d (this one is the equation to find out d when x is any integer)
     e
     

de = 1 + x.lambda

de - 1 = x.lambda

de - 1
------- = x (this one is to check whether the value obtained by the above equation is true or not by checking if x is the same value we had chosen for our calculation in the first place)
lambda

在做完这个检查后,我发现我在反方程中得到的 x 的值是不相等的,而是近似于我生成的原始随机值。

例如取这些值:

e = 327
lambda = 484
x = 76

We get d as 112.0

later We reverse The equation to find the value of x to confirm

we get:
x = 75.667355372 (Which is approximate to the original value)

我不知道哪里出了问题。

要查看完整程序,请访问this 链接。

如果我在这里做错了什么,请告诉我。

提前谢谢你!

【问题讨论】:

  • 您可以从使用 double 而不是 float 开始以获得更好的精度。
  • @assylias 确实我做到了,但它还是一样,所以我切换到浮动

标签: java modulo


【解决方案1】:

好的,我得到了这个问题的答案。 问题是我正在对integer 执行算术运算,所以我得到的结果是integer

我后来没有使用integer,而是使用Double进行同样的操作,我解决了这个问题。

public static int privatekey(Double primeprod, Double e, Double lambda)
{
    Random random = new Random();
    float d = 0;
    //extended euler's theorem is
    //d = (1 + x*lambda) / e
    //d is smaller than primeprod
    while(true)
    {
        int d = random.nextInt(200) + 1;
        System.out.println("seed: "+x);
        var = (1 + (x*lambda)) / e;
        System.out.println("var: "+d);
        if(isInteger(d) && d < primeprod)
        {
            break;
        }
    }
    int finalvar = (int)d;
    return finalvar;
}

这解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多