fix hàm nhân sửa hàm tìm d
unknown
java
5 years ago
3.3 kB
10
Indexable
// hàm tìm d khi biết q, p
static BigInteger modInverse(BigInteger e, BigInteger q, BigInteger p)
{
BigInteger m = multiply(q,p);
BigInteger m0 = m;
BigInteger y = new BigInteger("0"), x = new BigInteger("1");
BigInteger zero = new BigInteger("0");
BigInteger one = new BigInteger("1");
if (m.compareTo(one) == 0)
return zero;
while (smaller(BigInteger.ONE,e)) {
// q1 is quotient
BigInteger q1 = e.divide(m);
BigInteger t = m;
// m is remainder now, process
// same as Euclid's algo
m = e.mod(m);
e = t;
t = y;
// Update x and y
y = subtract(x,multiply(q1,y));
x = t;
}
// Make x positive
if (smaller(x,zero))
x = add(x,m0);
return x;
}
// fix lại hàm multiply
//Multiplication
static public BigInteger multiply(BigInteger op1, BigInteger op2)
{
String sOp1 = op1.toString();
String sOp2 = op2.toString();
int len1 = sOp1.length();
int len2 = sOp2.length();
// will keep the result number in vector
// in reverse order
int result[] = new int[len1 + len2];
// Below two indexes are used to
// find positions in result.
int i_n1 = 0;
int i_n2 = 0;
// Go from right to left in num1
for (int i = len1 - 1; i >= 0; i--)
{
int carry = 0;
int n1 = sOp1.charAt(i) - '0';
// To shift position to left after every
// multipliccharAtion of a digit in num2
i_n2 = 0;
// Go from right to left in num2
for (int j = len2 - 1; j >= 0; j--)
{
// Take current digit of second number
int n2 = sOp2.charAt(j) - '0';
// Multiply with current digit of first number
// and add result to previously stored result
// charAt current position.
int sum = n1 * n2 + result[i_n1 + i_n2] + carry;
// Carry for next itercharAtion
carry = sum / 10;
// Store result
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
// store carry in next cell
if (carry > 0)
result[i_n1 + i_n2] += carry;
// To shift position to left after every
// multipliccharAtion of a digit in num1.
i_n1++;
}
// ignore '0's from the right
System.out.println(result.length);
int i = result.length - 1;
while (i >= 0 && result[i] == 0)
i--;
// genercharAte the result String
String str3 = "";
while (i >= 0)
str3 += (result[i--]);
// return BigInteger("0") vd 1*0 = 0
if (str3.length() == 0)
return BigInteger.ZERO;
BigInteger ketqua = new BigInteger(str3);
return ketqua;
}Editor is loading...