Please explain why 17 % 40 = 17 - java

I am new to Java, actually programming in general. I understand that the modulus operator (%) returns the remainder of two numbers, however, I do not understand why 17 % 40 = 17.
I understand that 40 % 17 = 6, and 17 % 5 = 2, and 40 % 5 = 0. I get the gist of what value is returned as the remainder. But 17 % 40 = 17 has me stumped.
The only rationalization I can devise is that since the remainder is less than 1 the total value 17 is returned, why not 0? Please help to explain this enigma to me.

When you divide 17/40, quotient is 0 and the remainder is 17.
The modulo operator (%) returns the remainder.
i.e
a % b = remainder of a / b

Equation from Wiki by Knuth:
a = 17
n = 40
floor(a/n) = 0
so r = 17
When n > a then r is simply a.

i guess learning back the 3rd and 4th standard maths is the key point.
if u see (hope understand the division syntax. its the popular 3rd std way )
____
40)17
you will get a reminder 17 as 17 is not divisible by 40.
then there will be an adition of '.' and then the fraction will be added

If you have the numbers a and b, their quotient q and remainder r, then the following has to be true:
q · b + r = a
That is, if you multiply the quotient (q) by the divisor (b) and add the remainder (r), the result is the dividend (a).
In your case a = 17, b = 40, q = 0 and so r has to be 17.
Note: the equation above is just a rearrangement of the equation from Nikolay Kuznetsov's answer, but I think it's easier to understand this way.

Maybe this is a different and more helpful way to think about it.
When we apply division to integer numbers a and b, we are really trying to relate a and b like this:
a = Q * b + R
a is some multiple of b, plus some leftover. Q and R are integers; to keep this simple, let's also just think of non-negative numbers. The multiple, Q, is the quotient and leftover, R, is the remainder -- the smallest ones that make this relation work.
In most languages, a / b gives you Q, and and a % b gives you R. (In fact processors tend to compute both at once -- these are so related.)
So if a is 17 and b is 40, it only works if you write:
17 = 0 * 40 + 17
This is why a % b must be 17.
(Note that it gets more complex when considering negative numbers.)

Related

Getting negative integer values while using Random class to generate random positive integers [duplicate]

In java when you do
a % b
If a is negative, it will return a negative result, instead of wrapping around to b like it should. What's the best way to fix this? Only way I can think is
a < 0 ? b + a : a % b
It behaves as it should a % b = a - a / b * b; i.e. it's the remainder.
You can do (a % b + b) % b
This expression works as the result of (a % b) is necessarily lower than b, no matter if a is positive or negative. Adding b takes care of the negative values of a, since (a % b) is a negative value between -b and 0, (a % b + b) is necessarily lower than b and positive. The last modulo is there in case a was positive to begin with, since if a is positive (a % b + b) would become larger than b. Therefore, (a % b + b) % b turns it into smaller than b again (and doesn't affect negative a values).
As of Java 8, you can use Math.floorMod(int x, int y) and Math.floorMod(long x, long y). Both of these methods return the same results as Peter's answer.
Math.floorMod( 2, 3) = 2
Math.floorMod(-2, 3) = 1
Math.floorMod( 2, -3) = -1
Math.floorMod(-2, -3) = -2
For those not using (or not able to use) Java 8 yet, Guava came to the rescue with IntMath.mod(), available since Guava 11.0.
IntMath.mod( 2, 3) = 2
IntMath.mod(-2, 3) = 1
One caveat: unlike Java 8's Math.floorMod(), the divisor (the second parameter) cannot be negative.
In number theory, the result is always positive. I would guess that this is not always the case in computer languages because not all programmers are mathematicians. My two cents, I would consider it a design defect of the language, but you can't change it now.
=MOD(-4,180) = 176
=MOD(176, 180) = 176
because 180 * (-1) + 176 = -4 the same as 180 * 0 + 176 = 176
Using the clock example here, http://mathworld.wolfram.com/Congruence.html
you would not say duration_of_time mod cycle_length is -45 minutes, you would say 15 minutes, even though both answers satisfy the base equation.
Java 8 has Math.floorMod, but it is very slow (its implementation has multiple divisions, multiplications, and a conditional). Its possible that the JVM has an intrinsic optimized stub for it, however, which would speed it up significantly.
The fastest way to do this without floorMod is like some other answers here, but with no conditional branches and only one slow % op.
Assuming n is positive, and x may be anything:
int remainder = (x % n); // may be negative if x is negative
//if remainder is negative, adds n, otherwise adds 0
return ((remainder >> 31) & n) + remainder;
The results when n = 3:
x | result
----------
-4| 2
-3| 0
-2| 1
-1| 2
0| 0
1| 1
2| 2
3| 0
4| 1
If you only need a uniform distribution between 0 and n-1 and not the exact mod operator, and your x's do not cluster near 0, the following will be even faster, as there is more instruction level parallelism and the slow % computation will occur in parallel with the other parts as they do not depend on its result.
return ((x >> 31) & (n - 1)) + (x % n)
The results for the above with n = 3:
x | result
----------
-5| 0
-4| 1
-3| 2
-2| 0
-1| 1
0| 0
1| 1
2| 2
3| 0
4| 1
5| 2
If the input is random in the full range of an int, the distribution of both two solutions will be the same. If the input clusters near zero, there will be too few results at n - 1 in the latter solution.
Here is an alternative:
a < 0 ? b-1 - (-a-1) % b : a % b
This might or might not be faster than that other formula [(a % b + b) % b]. Unlike the other formula, it contains a branch, but uses one less modulo operation. Probably a win if the computer can predict a < 0 correctly.
(Edit: Fixed the formula.)

Modulo division vs remainder division java

I have learned a lot from my last question hopefully I don't make the same mistakes again:)
This stems from a previous question. Here is what I THINK I know:
For ints in java (I assume in all languages but I’m asking in JAVA specifically):
1/3 = 0
1%3 = 1
I was stumped as to why i%j = i when i < j and a previous poster explained how this worked and also stated that "First, in Java, % is the remainder (not modulo) operator, which has slightly different semantics...."
Their explanation was perfect for what I needed. However, I was confused by their quote because I was always taught that in mathematics modular == remainder division.
How does one execute modular division in JAVA and are there pitfalls to watch for when trying to use % as a modulus operator?
mathematicaly, modulo is division with remainder.
7 mod 4 = 1 R3
see:
n = a * m + r
The modulo operator in Java (like in most other languages) gives only the remainder part and not i dont know, if it works with negative numbers correct.
In Detail, mathematicaly the modulo is allways positive. That is the differece to the modulo operator in java.
a mod n = b, if there is a number k existing with a = b + kn
and 0 <= b < n
That means, if you take -14 mod 4:
-14 = b + k * 4 //lets take -3 for k
-14 = b + -3 * 4
-14 = b - 12
-2 = b
that would be wrong (mathematically) becaouse b is negative.
so we need to take -4 for k
-14 = b + -4 * 4
-14 = b + 16
2 = b
that is the correct answer. In this case only the sign is the difference, but if you take -15 mod 4 you will get -3 in java and most other languages, but the mathematically correct answer would be 1 (-15 + 16)
using java, you will get the negative values.
You may be confused by the "modulo operator" in arithmetic, which is the same as the % operator in Java and similar languages, I don't think there is such thing as "modular division". The % operator in java will always return the integer remainder from repeated division between two numbers. Just like in arithmetic, (i % j) = i where i < j and i >= 0. The result of the operation is less than j.

How to calculate ((Integer)^(double)) % (Integer) in java?

I am trying to calculate the value of (10^5.102103)%24 that is 10 raised to power 5.102103 modulus 24 in Java ?
Which is the best and accurate method to do because
int a;
double b;
int m;
Calculate (a^b)%m
Where a can be very large like upto 10^9
b can be any double or float value which can be large
and m is any Integer
Example ---How you can calculate the value of
(10^10002.3443)%10000007
I know Math.pow(a,b) function works for small a and b only
While BigInteger function Uses only modPow(a,b) where a and b should be integer only(Correct me if i am wrong)
Unfortunately, it's not possible using the normal Java data types to get a correct answer to this. If you use double to store the exponent, you introduce an error, because double won't store most decimal numbers exactly. When you write double b = 10002.3443; the number that is stored in b is actually 10002.34430000000065774656832218170166015625. Even though it looks like 10002.3443 when you print it, that's a trick of the way Java prints numbers - basically it chooses the decimal number with the least number of decimal places that would be represented by that double.
Now this difference looks insignificant. But the difference between 10^10002.3443 and 10^10002.34430000000065774656832218170166015625 is approximately 3.346 x 10^9990, which is a 9991-digit number. Now, what will this difference become when we apply the modulus operator?
(10^10002.34430000000065774656832218170166015625 % 10000007) - (10^10002.3443 % 10000007)
= (10^10002.34430000000065774656832218170166015625 - 10^10002.3443) % 10000007
= (3.346 x 10^9990) % 10000007 (approximately)
Now, it's anybody's guess what that actually comes to. But you've got a better chance of being struck by lightning than of getting the correct answer, if you use double at any point in the calculation.
The other option might be BigDecimal. But the problem is that 10^10002.3443 is irrational - it's not a terminating decimal, so it can't be represented correctly in a BigDecimal.
So Java doesn't have a data type that will allow you to perform the calculation that you want to perform.
You are going to have to invent your own data type, then work out how to do all the bit-crunching to implement exponentiation and modulus. This is a huge project, and I suggest you start out by getting yourself a PhD in mathematics.
(Note: Obviously, I am using ^ to indicate exponentiation and x to indicate multiplication in the above, even though this is not the normal Java convention)
Let's think back to discrete math!
Given y = a b (mod m), we know that
y = ((a mod m)^b) mod m
For example, if we have
a = 2, b = 6, m = 5
a raised to the power of b is 64. 64 mod m is 64 % 5 == 4. Let's check our algorithm:
4 == ((a mod m)^b) mod m
4 == ((2 mod 5)^6) mod 5
...
4 == 64 % 5
4 == 4
This doesn't really help us all too much (in its current form), so let's use modular arithmetic at every step to save the day.
int a = 10;
int m = 10000007;
double b = 10002.3443;
int holder = (int) b;
double delta = b - holder; // as close as we're going to get
int total = 1;
for (int i = 0; i < holder; i++) {
total *= (a % m); // multiply by the modulus
total %= m; // take the modulus again
}
total *= (Math.round(Math.pow(a, delta)) % m);
total %= m;

A mathematical function that gets us the number of leaves of a specific type of k-ary?

I am trying to figure out a function f(x) that would calculate the number of leaves in a k-ary tree. For example, assume we created a tree that began with root 4 with 3 children, each of -1,-2,-3 respectively. Our leaves would only be 0 values, not null values. I have spent the past day trying to figure out a function and it seems like nothing I do goes in the correct direction.
EX:
4
/ | \
3 2 1
/ |\ /| /
2 1 0 1 0 0
/| / /
1 0 0 0
/
0
7 Leaves.
Any help would be very much appreciated! Thanks!
To clarify, I need a mathematical equation that derives the same answer as code would if I recursively transversed the tree.
More examples:
{4,7}{5,13}{6,24}{7,44}{8,81}{9,149}{10,274}{11,504}{12,927}{13,1705}{14,3136}{15,5768}{16,10609}{17,19513}{18,35890}{19,66012}{20,121415}
public int numleaves(TreeNode node) {
if (node == null)
return 0;
else if (node.getLeft() == null && node.getMiddle() == null && node.getRight() == null)
return 1;
else
return numleaves(node.getLeft()) + numleaves(node.getMiddle()) + numleaves(node.getRight());
}
I cannot answer your question, but it has a solution. I can only outline the case for the number of children k being equal to 2. The case k=3 leads to a cubic polynomial with two complex and one real solution, I lack the tools here to derive them in a non-numerical way.
But let's have a look at the case k=2. Interestingly, this problem is very closely related to the Fibonacci numbers, except for having different boundary conditions.
Writing down the recursive formula is easy:
a(n) = a(n-1) + a(n-2)
with boundary conditions a(1)=1 and a(0)=1. The characteristic polynomial of this is
x^2 = x + 1
with the solutions x1 = 1/2 + sqrt(5)/2 and x2 = 1/2 - sqrt(5)/2. It means that
a(n) = u*x1^n + v*x2^n
for some u and v is the explicit formula for the sequence we're looking for. Putting in the boundary conditions we get
u = (sqrt(5)+1)/(2*sqrt(5))
v = (sqrt(5)-1)/(2*sqrt(5))
i.e.
a(n) = (sqrt(5)+1)/(2*sqrt(5))*(1/2 + sqrt(5)/2)^n + (sqrt(5)-1)/(2*sqrt(5))*(1/2 - sqrt(5)/2)^n
for k=2.
Your code seems to be computing a Tribonacci sequence with starting values 1, 1 and 2. This is sequence A000073 from the On-Line Encyclopedia of Integer Sequences, starting from the third entry of that sequence rather than the first. The comments section of the encyclopedia page gives an explicit formula: since this is a linear recurrence relation with a degree 3 characteristic polynomial, there's a closed form solution in terms of the roots of that polynomial. Here's a short piece of Python 2 code based on the given formula that produces the first few values. (See the edit below for a simplification.)
from math import sqrt
c = (1 + (19 - 3 * sqrt(33))**(1/3.) + (19 + 3 * sqrt(33))**(1/3.)) / 3.
m = (1 - c) / 2
p = sqrt(((3*c - 5)*(c+1)/4))
j = 1/((c-m)**2 + p**2)
b = (c - m) / (2 * p*((c - m)**2 + p**2))
k = complex(-j / 2, b)
r1 = complex(m, p)
def f(n):
return int(round(j*c**(n+2) + (2*k*r1**(n+2)).real))
for n in range(0, 21):
print n, f(n)
And the output:
0 1
1 1
2 2
3 4
4 7
5 13
6 24
7 44
8 81
9 149
10 274
11 504
12 927
13 1705
14 3136
15 5768
16 10609
17 19513
18 35890
19 66012
20 121415
EDIT: the above code is needlessly complicated. With the round operation, the second term in f(n) can be omitted (it converges to zero as n increases), and the formula for the first term can be simplified. Here's some simpler code that generates the same output.
s = (19 + 297**0.5)**(1/3.)
c = (1 + s + 4/s)/3
j = 3 - (2 + 1/c)/c
for n in range(0, 32):
print n, int(round(c**n / j))
I can't help it, but I see Binomial tree in it. http://en.wikipedia.org/wiki/Binomial_heap
I think that good approximation could be sum of k-th row of pascal triangle, where k stands for the number of the root node.
Isn't this easier to understand:
We set the starting values for the tribonacci sequence into a list called result. Then we put these values into 3 variables. We change the variable content based on the tribonacci formula (new a is a+b+c, new b is old a, new c is old b). Then we calculate to whatever tribonacci number we want to go up to and store each result into our result list. At the end, we read out the indexed list.
result=[1,1,2]
a,b,c=result[-1],result[-2],result[-3]
for i in range(40):
a,b,c=a+b+c,a,b
result.append(a)
for e,f in enumerate(result):
print e,f

Converting from number to hexavigesimal letters?

I'm trying to re-order some Excel columns using JExcel. I also need to find references to other cells and then re-map them to reference the correct cells. I feel like I've done a lot of the hard work, but I've hit a stumbling block.
I found this code on wikipedia, as linked to from SO:
public static String toBase26(int number){
number = Math.abs(number);
String converted = "";
// Repeatedly divide the number by 26 and convert the
// remainder into the appropriate letter.
do
{
int remainder = number % 26;
converted = (char)(remainder + 'A') + converted;
number = (number - remainder) / 26;
} while (number > 0);
return converted;
}
But when I run the number 35 into it, this is what happens:
number = 35
remainder = 9
converted= char(9+'A')+"" = J
number = (35-9)/26 = 1
1>0
remainder = 1
char(1+'A') = B
converted= char(1+'A')+"J" = BJ
Which is, in a way expected, as Base 10 (35) = Base 26 (19). But I'm actually wanting to refer to column AJ.
I can't untangle what change I need to make to get the right letters out. Whenever I try to work it out on paper, I end up ruining the previous letters extracted. For instance, I don't think this would work, as it means I end up with remainder as 8, the first time, and then that would be converted into I, unless I've missed something?
Any help on this would be greatly appreciated. I've looked around and wasted enough time on this. I just want some help to get it to work.
The stumbling block behind this 'hexavidecimal system' is that it has a 0, but the units column skips the 0 and ranges only from A-Z. Consider the following conversion from decimal:
A 1 (0*26 + 1)
...
Z 26 (0*26 + 26)
AA 27 (1*26 + 1)
...
AZ 52 (1*26 + 26)
BA 53 (2*26 + 1)
...
BZ 78 (2*26 + 26)
CA 79 (3*26 + 1)
...
ZZ 702 (26*26 + 26)
AAA 703 (1*26*26 + 1*26 + 1)
See the problem? There are missing 'zeroes' in the hexavidecimal numbers:
00A 1
...
00Z 26
0AA 27
...
0AZ 52
0BA 53
...
0BZ 78
0CA 79
...
0ZZ 702 (26*26 + 26)
AAA 703 (1*26*26 + 1*26 + 1)
However, the units column does NOT have the zeroes ever!
Obviously we do not print these zeroes, but it should aid your understanding of what is going wrong.
Here's our algorithm. I wrote the algorithm under the assumption that decimal 0 = hexavidecimal A, 1 -> B, 25 -> Z, 26 -> AA and so on because it makes it easier for me to wrap my head around. If this isn't the assumption you want just subtract 1 before running the code :)
0. If number =< 0, return.
1. Modulo by 26. Convert 0-25 to 'A'-'Z'. //This is our units column.
Loop {
2. Divide the number by 26 (integer division rounding down).
3. If number =< 0, return.
4. Modulo by 26. Convert 0-25 to 'Z','A'-'Y'. //This is our next column (prepend to string output).
}
Example
Converting decimal 730 -> ABC hexavigesimal
Modulo of 730 by 26 = 2 -> 'C' for units column
Divide 730 by 26 = 28
Modulo 28 by 26 = 2 -> 'B' for tens column
Divide 28 by 26 = 1
Modulo 1 by 26 = 1 -> 'A' for hundreds column
Divide 1 by 26 = 0
Number is empty, therefore return 'ABC'
Here is a simple Python function to compute the hexavigesimal representation of a number (in an arbitrary base), where a is equal to 1 (not 0).
The tricky part of the problem is that at each step you're taking between 1 and 10 off the remainder, so you need to account for that in your modulo. The code below accounts for it by subtracting 1 from the number each time. Then 0 becomes a very convenient end condition, because you cannot represent 0 in hexavigesimal (the wikipedia entry denotes it λ).
# Formats a number as a bijective base N string.
def bijective(n, base):
chars = ''
while n != 0:
chars = chr((n - 1) % base + 97) + chars
n = (n - 1) / base
return chars
# Examples!
if __name__ == '__main__':
base = 26
for n in range(1, 2 * base * base):
print('{}: {}'.format(n, bijective(n, base)))
See it in action on pythonanywhere.
I included a javascript version in this gist.

Categories

Resources