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.
Related
I came across this solution to checking if a number is pandigital(an n-digit number that makes use of all the digits 1 to n exactly once, eg.1234).
private boolean isPandigital(int n){
int digits = 0;
int numDigits = String.valueOf(n).length();
for (; n > 0; n /= 10){
digits += (1 << (n - ((n / 10) * 10) - 1));
}
return digits == ((1 << numDigits) - 1);
}
The for loop takes a digit off n each loop(1234,123,12,1). Inside the loop:
(n - ((n / 10) * 10) - 1)
evalutes to the last digit of n and takes away 1.
I understand what the method is physically doing but what property of pandigital numbers is it exploiting?
The property it's exploiting is that for a pandigital input of length n, summing the digits must equal (n + (n - 1) + (n - 2) ... + 1) which is equivalent to (n * (n + 1)) / 2. But instead of doing the algorithm in decimal the function is doing it with binary bits.
It uses each decimal digit to increment a binary digit. For a decimal digit d the binary bit at (d - 1) gets incremented. i.e. the decimal digit 3 becomes (1 << (3 - 1)) which will increment the 2nd binary digit. These are summed and compared to the expected value. The expected value is that every binary digit will be set for the length of your input. If your input is 1234 every binary bit will be set for a 4 bit binary value (1111 in binary = 15 in decimal from ((1 << numDigits) - 1)).
No specific property is used.
The trick is that when you find a digit i, you add (2 to the power i) to the variable digits, i.e setting a single bit in this integer. At the end of the process, number of n digits wiil be pandigital, if digits = (2 to the power i) -1, i.e. the n low bits of digits all set to 1.
Just for fun, you may do it in a recursive way:
bool ispandigital = testpandigital(n.ToString()) ;
private bool testpandigital(string nbr)
{
string digit=str.Length.ToString() ;
return nbr=="0" || (nbr.Contains(digit) && testpandigital(nbr.Replace(digit,"")) ;
}
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;
}
While i was searching for Exponentiation by squaring i got the recursive method there but then i stumbled upon this pseudo code , Which i'm unable to understand fully.
function powermod(base, exponent, modulus) {
if (base < 1 || exponent < 0 || modulus < 1)
return -1
result = 1;
while (exponent > 0) {
if ((exponent % 2) == 1) {
result = (result * base) % modulus;
}
base = (base * base) % modulus;
exponent = floor(exponent / 2);
}
return result;
}
if you can give some insight in simple terms it will be of great help
The code relies on the fact that:
x^y == (x*x)^(y/2)
The loop is doing exactly that: dividing the exponent by two while squaring the base.
An example:
Let's consider computing the result of 3^13. You can write the exponent (13) as a sum of binary powers: 3^(8+4+1). Then: 3^13 = 3^8 * 3^4 * 3^1.
This decomposition in binary powers is done by the %2, /2 done in the code, using the rationale exponained above.
Step by step:
You start with 3^13. As 13%2==1, you multiply the result by 3, because the answer does have a factor 3^1.
Then you divide the exponent by 2 and square the base (9^6 == 3^12). As 6%2==0, this means the answer doesn't have a factor 3^2.
Then you divide the exponent by 2 and square the base (81^3 == 3^12). As 3%2==1, you multiply the result by 81 because the answer does have a factor 3^4.
Then you divide the exponent by 2 and square the base (6561^1 == 3^8). As 1%2==1, you multiply the result by 6561 because the answer does have a factor 3^8.
Assume you want to calculate x^y with y in Z. Note y=y/2+y%2 (using "/" as integer division an "%" as modulus).
a) if y == 0 then x^y=1; if y==1 then x^y=x; if y==-1 then x^y=1/x.
b) If y%2 == 0 then x^y = (x^2)^(y/2) => square x (x'=x^2), divide y by two (y'=y/2), and apply recursively the algorithm to calculate x'^y' = x^y.
c) If y%2 == 1 then x^y = (x^2)*((x^2)^(y/2)) => square x (x'=x^2), divide y by two (y'=y/2), and apply recursively the algorithm to calculate x'^y', and after x^y = x'*(x'^y').
In this way, using only integer division and square of values you can calculate any exponential.
Example: x^19
1) 19%2==1 [rule c] => x^19=x'*(x'^9) where x' = x^2.
2) 9%2==1 [rule c] => x'^9=x''*(x''^4) where x'' = x'^2.
3) 4%2==0 [rule b] => x''^4=x'''^2 where x''' = x''^2.
4) 2%2==0 [rule b] => x'''^2 = x''''^1 where x''''=x'''^2.
5) x''''^1 [rule a] is immediate.
if the calculus is done over a finite field of integers mod n, the logic is the same.
Addendum
In fact, same logic can be used to the more simple calculus and more easy to understand problem of a number multiplied by an integer: x*y.
a) if y == 0 then x*y=0; if y==1 then x*y=x; if y==-1 then x*y=-x.
b) If y%2 == 0 then x*y = (x*2)*(y/2) => multiply x by 2 (x'=x*2), divide y by two (y'=y/2), and apply recursively the algorithm to calculate x'*y' = x*y.
c) If y%2 == 1 then x*y = (x*2)+(x*2)*(y/2) => multiply x (x'=x*2), divide y by two (y'=y/2), apply recursively the algorithm to calculate x'*y', and after x*y = x'+x'*y'.
int way, product is reduced to addition and shift operations.
here:
public class maths
{
private float Base;
private float Exponent;
private float Modulus;
private float Result;
public float powermod(float base, float exponent, float modulus)
{
if (base < 1 || exponent < 0 || modulus < 1)
{
return -1;
}
while (exponent > 0)
{
if ((exponent % 2) == 1)
{
Result = (Result * base) % modulus;
}
base = (base * base) % modulus;
exponent = floor(exponent / 2);
}
return Result;
}
public static void main(String[] args) {
maths m = new maths();
System.out.println( m.powermod(0, 1, 2));
System.out.println( m.powermod(1, 2, 3));
System.out.println(m.powermod(3, 3, 3));
System.out.println(m.powermod(4, 4, 4));
}
}
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.