模块化逆 - java编码

时间:2011-02-03 14:54:02

标签: java math

请帮忙。我一直在努力,不能正确。我遇到的问题是我得到的逆输出总是1。

这是我的代码(它计算GCD并尝试修改,因此它也计算^ -1):

import java.util.Scanner;

public class scratchwork
{


    public static void main (String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        long n, a, on, oa;
        long gcd = 0;

        System.out.println("Please enter your dividend:");
        n= keyboard.nextLong();

        System.out.println("Please enter your divisor:");
        a= keyboard.nextLong();

        on= n;
        oa= a;

        while (a!= 0)
                {gcd=a;
                    a= n% a;
                    n= gcd;
        }

        System.out.println("Results: GCD(" + odd + ", " + odr + ") = " + gcd);

        long vX; vS; vT; vY; q; vR; vZ; m; b;

        vX = n; vY=a;
        vS = 0; vT = 1; m=0; b=0;
        while (a != 0)
        {
            m=vT;;
                b=vX;
                q = n / a;
                vR = vS - q*vT;
                tZ = n - q*a;
                vS = vT; n = da;
                vT = tY; dY = vZ;

        }

         if (d>1) System.out.println("Inverse does not exist.");
        else System.out.println("The inverse of "+oa+" mod "+on+" is "+vT);
    } 
}

4 个答案:

答案 0 :(得分:0)

我们能看到变量声明吗?如果将整数与double混合,则可以舍入数字。无论如何,如果你只想要逆,juste使用Math.pow(a, -1);

此外,在第二个循环中,您永远不会设置“a”,因此它将永远循环:

while (a != 0)
        {
            m=vT;;
                b=vX;
                q = n / a;
                vR = vS - q*vT;
                tZ = n - q*a;
                vS = vT; n = da;
                vT = tY; dY = vZ;

        }

答案 1 :(得分:0)

您发布的代码并未声明它使用的大多数变量,因此无法编译。最重要的是,它用于输出结果的变量v既未定义也未分配给已发布代码中的任何位置 - 无论它包含什么都与计算无关。

答案 2 :(得分:0)

@Justin, 谢谢。我能够弄清楚如何在每个循环中打印出变量。我基本上不得不把我的循环放在GCD循环中......就是这样。 2周的工作,我只需要移动循环。

有效!对不起,我在这里做了一个快乐的舞蹈。

答案 3 :(得分:0)

这是Python中的一个解决方案,应该可以轻松地转换为Java:

def euclid(x, y):
    """Given x < y, find a and b such that a * x + b * y = g where, g is the
    gcd of x and y.  Returns (a,b,g)."""
    assert x < y
    assert x >= 0
    assert y > 0

    if x == 0:
        # gcd(0,y) = y
        return (0, 1, y)
    else:
        # Write y as y = dx + r
        d = y/x
        r = y - d*x

        # Compute for the simpler problem.
        (a, b, g) = euclid(r, x)

        # Then ar + bx = g     -->
        #      a(y-dx) + bx = g    -->
        #      ay - adx + bx = g    -->
        #      (b-ad)x + ay = g
        return (b-a*d, a, g)

def modinv(x, n):
    (a, b, g) = euclid(x%n, n)
    assert g == 1

    # a * x + b * n = 1 therefore
    # a * x = 1 (mod n)
    return a%n

它使用堆栈,但Euclid的算法采用O(log n)步骤,因此除非您的数字是天文数字高,否则不会有堆栈溢出。也可以通过一些努力将其转换为非递归版本。

相关问题