How do I compute F(n)%mod where mod is a prime number.
and F(n)=n!/(q!^r)%mod....(x^r stands for pow(x,r)).
I'm trying it with fermat's little theorem for computing the inverse modulo but the problem I'm facing is that fermat is applicable only if gcd(denominator,mod)=1.
So is there any other way to solve this.
If the modulus is prime, you can compute the inverse using the extended Euclidean algorithm:
function inverse(x, m)
a, b, u = 0, m, 1
while x > 0
q = b // x # integer division
x, a, b, u = b % x, u, x, a - q * u
if b == 1 return a % m
error "must be coprime"
If the modulus is composite, this algorithm will still work as long as x and m are coprime. If they share a factor, then the inverse does not exist.
There is no modular inverse if the gcd is not 1. Right at the top of the Wikipedia page:
The multiplicative inverse of a modulo m exists if and only if a and m are coprime (i.e., if gcd(a, m) = 1).
As you are trying to compute this quotient modulo p (for a certain prime), let me assume that you know the result is an integer.
As people have mentioned, if q >= p, then you cannot compute the inverse of the denominator, as q! is not coprime with the modulo, so this number is not invertible. But that does not mean that you cannot compute the whole quotient modulo p.
Let a, b be the number of p factors in the numerator and the denominator, respectively. As the result is an integer, we have a >= b. If the inequality is strict, then the result is 0. Otherwise, if equality holds we can remove those factors from numerator and denominator and proceed, as now the denominator is coprime with p.
So let me start with the method for computing those a, b numbers efficiently. The key is known as De Polignac's formula, and it says that for a given k, the number of p factors in k! can be calculated like this:
int polignac(int k, int p) {
int res = 0, power = p;
while (k >= power) {
res += k/power;
power *= p;
}
return res;
}
So with this we obtain the p factors for both n! and q!, so it is trivial to obtain the p factors of q!^r (just multiply by r).
In the strict inequality case, we are done. If not, we have to compute the modulo of both numerator and denominator "dropping" all the p factors. This can also be efficiently solved. We can write k! like this:
k! = 1 x 2 x 3 x ... x p x (p + 1) x (p + 2) ... x (p^2) x ...
If we remove the p factors and apply modulo, we have the following:
k! = 1 x 2 x 3 x ... x (nothing here, just a 1) x 1 x 2 ... x (another 1) x ...
Therefore, the same product keeps repeating until the end. So calculate 1 x 2 x ... x (p - 1) modulo p, raise it to the proper power modulo p (using fast exponentiation) and just multiply it be the "reamaining" terms, as in general k is not divisible by p.
Related
I have created a method that allows me to find the GCF/GCD of two numbers, and although I have a working code, I don't know how or why it works. I understand Euclid's algorithm, but am not sure how the following snippet uses it.
private int gcd(int a, int b)
{
if (b == 0)
return a;
else if(a ==0)
return b;
else
return gcd(b, a % b);
}
I am especially confused on what it is returning, because why are were returning two values? And what does the a % b do? How does this use Euclid's algorithm?
"the greatest common divisor of two numbers does not change if the
larger number is replaced by its difference with the smaller number."
(wikipedia - Euclidean algorithm)
So, modulo:
Modulo returns the remainder of the integer divison between two integers. Integer division is divison without fractions or floating points. Let's denote integer division as m /\ n.
m /\ n = o;
m % n = p;
o * n + p = m;
As an example,
29 /\ 3 = 9; (3 goes - whole - into 29 9 times)
29 % 3 = 2; (the integer division of 29 into 3 has a remainder of 2)
9 * 3 + 2 = 29; (9 goes into 29 3 times (and 3 goes into 29 9 times), with a remainder of 2)
Note that if m is smaller than n (i.e. m < n), then n goes into m 0 times (m /\ n = 0), so the remainder of the integer division will be m (m % n = m, because o * n + p = m and so (0*n) + p = 0 + p = p = m);
So, how does the function work? let's try using it.
1 - gcd(m, n), m < n
So, if we start out gcd(m, n) with an m that is smaller than n, the only thing that happens on the next nested call to gcd is that the order of the arguments changes: gcd(n, m % n) = gcd(n, m);
2 - gcd(n, m), m < n
Okay, so now the first argument larger than the second.
According to euclid's algorithm, we want to do something to the larger of the two numbers. We want to replace it with the difference between it and the smaller number. We could do m - n a bunch of times. But what m % n does is the exact same as subtracting n from m as many times as possible before doing so would result in a negative number. Doing a subtraction would look like (((m - n) - n) - n) - n) and so on. But if we expand that out, we get:
m - (n * o). Because o * n + p = m, we can see that m - (n * o) = p and p = m % n. So, repeatedly subtracting the smaller from the larger is the same as doing modulo of the larger with the smaller.
In the next step, the second argument may be 0 (if n was a divisor of m). In this case, the function returns n. this is correct because n is a divisor of itself and also, as we've seen, a divisor of m.
Or, the second argument may be smaller than n. That is because the remainder of the integer divison of m into n must be smaller than n - this is because, if the remainder of the division were larger than n, then n could have fit into m one more time, which it didn't; this is an absurd result. Assuming that n is not 0, then the second argument (let's call it p) is smaller than n.
So, we are now calling gcd(n, p), where p < n.
3 - gcd(n, p), p < n
What happens now? well, we are exactly in the same place as we were in the previous paragraph. Now we just repeat that step, i.e. we will continue to call gcd(a, b), until the smaller of the two numbers that are passed into gcd(a ,b) is a divisor of the larger of the two numbers, (meaning that a % b = 0) in which case you simply return the smaller of the two numbers.
1) What does the a % b do?
% is the modulus or remainder operator in Java. The % operator returns the remainder of two numbers. For example 8 % 3 is 2 because 8 divided by 3 leaves a remainder of 2.
2) The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. Actually, your gcd function is used a more efficient version of the Euclidean algorithm. This version instead replacing the larger of the two numbers by its remainder when divided by the smaller of the two (with this version, the algorithm stops when reaching a zero remainder). This was proven by Gabriel Lamé in 1844 (https://en.wikipedia.org/wiki/Euclidean_algorithm)
3) Your gcd function's not returning two values, it's a recursive function. The recursive function is a function which either calls itself or is in a potential cycle of function calls. In case of your gcd function, it will be repeat until one of two parameters become zero and the gcd value is the remain parameter.
You could learn more about recursive function at this link.
http://pages.cs.wisc.edu/~calvin/cs110/RECURSION.html
Given that your question has a few components, I’ll discuss the evolution of Euclid’s classical algorithm into the recursive method you presented. Please note that the methods presented here assume that a >= b
The method below most likely implements the algorithm that you are familiar with, which repeatedly subtracts b (the smaller number) from a (the larger number), until it is no longer larger or equal to b. If a == 0, there is no remainder, giving b as the GCD. Otherwise, the values of a and b are swapped and repeated subtraction continues.
public int classic_gcd(int a, int b) {
while (true) {
while (a >= b)
a = a - b;
if (a == 0)
return b;
int c = b;
b = a;
a = c;
}
}
Since the inner while loop, essentially calculates the reminder of a divided by b, it can be replaced with the modulus operator. This greatly improves the convergence rate of the algorithm, replacing a potentially large number of subtractions with a single modulus operation. Consider finding the GCD of 12,288 and 6, which would result in over 2,000 subtraction. This improvement is shown in the modified method below.
public int mod_gcd(int a, int b) {
while (true) {
int c = a % b;
if (c == 0)
return b;
a = b;
b = c;
}
}
Lastly, the modified algorithm can be expressed as a recursive algorithm, that is, it calls upon itself, as follows:
public int recurse_gcd(int a, int b) {
if (b == 0)
return a;
else
return recurse_gcd(b, a % b);
}
This method accomplishes the same as before. However, rather than looping, the method calls itself (which if not checked is an endless loop too). The swapping of values is accomplishing by changing the order of the arguments passed to the method.
Mind you, the methods above are purely for demonstration and should not be used in production code.
This program divides a number and calculates its quotient and remainder. But I'm getting odd results for the modulus operation.
public String operater(int arg1, int arg2) throws IllegalArgumentException
{
int quotient;
int remainder;
String resString;
// Check for Divide by 0 Error.
if(arg2 == 0)
{
throw new IllegalArgumentException("Illegal Argument!");
}
else
{
quotient = arg1 / arg2;
remainder = arg1 % arg2;
resString = "Quotient: " + Integer.toString(quotient) +
Remainder: " + Integer.toString(remainder);
}
return resString;
}
58585 / -45 gives the quotient as -1301 and remainder as 40. But Google says that 58585 % -45 = -5. I think the reason that there are special rules to dealing with signs when doing signs.
From Modulo Operations:
"However, this still leaves a sign ambiguity if the remainder is
nonzero: two possible choices for the remainder occur, one negative
and the other positive, and two possible choices for the quotient
occur. Usually, in number theory, the positive remainder is always
chosen, but programming languages choose depending on the language and
the signs of a and/or n.[6] Standard Pascal and ALGOL 68 give a
positive remainder (or 0) even for negative divisors, and some
programming languages, such as C90, leave it to the implementation
when either of n or a is negative. See the table for details. a modulo
0 is undefined in most systems, although some do define it as a."
I want to fix my program but, I don't understand what that means.
Depends on what you want. In math, and in some programming languages if the modulo is not zero, then it has the same sign as the divisor, treating integer division as truncating towards negative infinity. In other programming languages, if the modulo is not zero, it has the same sign as the dividend, treating integer division as truncating towards zero. Some programming languages include both a modulo operator (sign same as divisor) and remainder operator (sign same as dividend).
With the mathematical type of modulo, then r = (a + k*b)%b returns the same value for r regardless if k is negative, zero, or positive. It also means that there are only b possible values for any dividend modulo b, as opposed to the other case where there are 2*b - 1 possible values for a dividend modulo b, depending on the sign of the dividend.
C example to make modulo work the way it does in mathematics:
int modulo(int n, int p)
{
int r = n%p;
if(((p > 0) && (r < 0)) || ((p < 0) && (r > 0)))
r += p;
return r;
}
I was trying to use java's integer division, and it supposedly takes the floor. However, it rounds towards zero instead of the floor.
public class Main {
public static void main(String[] args) {
System.out.println(-1 / 100); // should be -1, but is 0
System.out.println(Math.floor(-1d/100d)); // correct
}
}
The problem is that I do not want to convert to a double/float because it needs to be efficient. I'm trying to solve this with a method, floorDivide(long a, long b). What I have is:
static long floorDivide(long a, long b) {
if (a < 0) {
// what do I put here?
}
return a / b;
}
How can I do this without a double/float?
floorDiv() from Java.Math that does exactly what you want.
static long floorDiv(long x, long y)
Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.
Take the absolute value, divide it, multiply it by -1.
Weird bug.
You can use
int i = (int) Math.round(doubleValToRound);
It will return a double value that you can cast into an int without lost of precission and without performance problems (casts haven't a great computational cost)
Also it's equivalent to
int a = (int) (doubleValToRound + 0.5);
//in your case
System.out.println((int) ((-1 / 100) + 0.5));
With this last one you won't have to enter into tedious and unnecesary "if" instructions. Like a good suit, its valid for every moment and has a higher portability for other languages.
This is ugly, but meets the requirement to not use a double/float. Really you should just cast it to a double.
The logic here is take the floor of a negative result from the integer division if it doesn't divide evenly.
static long floorDivide(long a, long b)
{
if(a % b != 0 && ((a < 0 && b > 0) || (a > 0 && b < 0)))
{
return (a / b - 1);
}
else
{
return (a / b);
}
}
Just divide the two integers. then add -1 to the result (in case the absolute value of both numerator and denominator are not same). For example -3/3 gives you -1, the right answer without adding -1 to the division.
Since a bit late, but you need to convert your parameters to long or double
int result = (int) Math.floor( (double) -1 / 5 );
// result == -1
This worked for me elegantly.
I would use floorDiv() for a general case, as Frank Harper suggested.
Note, however, that when the divisor is a power of 2, the division is often substituted by a right shift by an appropriate number of bits, i.e.
x / d
is the same as
x >> p
when p = 0,1,...,30 (or 0,1,...,62 for longs), d = 2p and x is non-negative. This is not only more effective than ordinary division but gives the right result (in mathematical sense) when x is negative.
This question already has answers here:
C: The Math Behind Negatives and Remainder
(2 answers)
Closed 9 years ago.
If I ask java for:
System.out.print(-0.785 % (2*Math.PI));
And print the result, it shows -0.785 when it should be printing 5.498... Can anyone explain me why?
The first operand is negative and the second operand is positive.
According to the JLS, Section 15.17.3:
[W]here neither an infinity, nor a zero, nor NaN is involved, the
floating-point remainder r from the division of a dividend n by a
divisor d is defined by the mathematical relation r = n - (d · q)
where q is an integer that is negative only if n/d is negative and
positive only if n/d is positive, and whose magnitude is as large as
possible without exceeding the magnitude of the true mathematical
quotient of n and d.
There is no requirement that the remainder is positive.
Here, n is -0.785, and d is 2 * Math.PI. The largest q whose magnitude doesn't exceed the true mathematical quotient is 0. So...
r = n - (d * q) = -0.785 - (2 * Math.PI * 0) = -0.785
Ok, I'm not going to explain it better than the other answer, but let's just say how to get your desired results.
The function:
static double positiveRemainder(double n, double divisor)
{
if (n >= 0)
return n % divisor;
else
{
double val = divisor + (n % divisor);
if (val == divisor)
return 0;
else
return val;
}
}
What's happening:
If n >= 0, we just do a standard remainder.
If n < 0, we first do a remainder, putting it in the range (-divisor, 0], then we add divisor, putting it in our desired range of (0, divisor]. But wait, that range is wrong, it should be [0, divisor) (5 + (-5 % 5) is 5, not 0), so if the output would be divisor, just return 0 instead.
I am trying to use Horner's rule to convert words to integers. I understand how it works and how if the word is long, it may cause an overflow. My ultimate goal is to use the converted integer in a hash function h(x)=x mod tableSize. My book suggests, because of the overflow, you could "apply the mod operator after computing each parenthesized expression in Horner's rule." I don't exactly understand what they mean by this. Say the expression looks like this:
((14*32+15)*32+20)*32+5
Do I take the mod tableSize after each parenthesized expression and add them together? What would it look like with this hash function and this example of Horner's rule?
The book is saying that you should take advantage of these mathematical equivalences:
(a * b) mod m = ((a mod m) * (b mod m)) mod m
(a + b) mod m = ((a mod m) + (b mod m)) mod m
Thus,
h = (((x*c) + y)*c + z) mod m
Is equivalent to
_ _ _ _
h = (((x*c) + y)*c + z)
Where
_
a * b = ((a mod m) * (b mod m)) mod m
_
a + b = ((a mod m) + (b mod m)) mod m
Essentially, for each basic addition and basic subtraction, you replace it with an "advanced" version that mod the operands, and mod the results. Since operands to the basic multiplication are now in the range of 0..m-1, the biggest number you'll get is (m-1)^2, which can alleviate overflow if m is small enough.
See also
Wikipedia:modular exponentiation
Wikipedia:modulo operation
-1 mod 2 = 1 mathematically, but -1 % 2 in Java is -1.
By the way, it should be pointed out that 32 is a terrible choice of multiplier for hash functions of this class (since it's not a prime), especially for computing (since it's a power of 2). Much better is 31, because:
It's prime (mathematically important!)
It's one less than a power of two, so it can be optimized to a cheaper shift and subtract
31 * i == (i << 5) - i
They mean replace the result of a parenthesized expression with that result mod tableSize:
((((14*32+15)%tableSize)*32+20)%tableSize)*32+5
It's easier to understand this using the Java code. We should apply the modulo operator at each step in the calculation inside the loop:
public static int hashCode(String key) {
int hashVal = 0;
for (int j = 0; j < key.length(); j++) {
// For small letters.
int letter = key.charAt(j) - 96;
hashVal = (hashVal * 32 + letter) % arraySize; // mod
}
return hashVal;
}