integer divison with negative remainder - math

I'm trying to find a name for mathematical division operation which can produce negative reminder.
Examples of expected:
5 %? 2 = 2*2 + 1
11 %? 3 = 4*3 - 1
module of reminder should be as small as possible.
Does someone knew the name of such operation?

Computer language remainder functions return a positive remainder. What you need is simple. In your second example you want is a remainder of -1.
11 %? 3 = 4*3 - 1
But what you get is a remainder of 2.
11 %? 3 = 3*3 + 2
As I said in the comments, check the remainder 2 against half the divisor 3/2 = 1.5. Since the remainder is greater than half the divisor, subtract the divisor:
2 - 3 = -1
Yes, you will have to store a real number for half the divisor.

Related

Largest Permutation in k steps (R)

I have a problem where I would like to replace 2 numbers in a set upto "k"-times such that each time they are switched, I get the largest possible permutation and print this after k-swaps. For example with k=2, for the set (1,4,2,5,3,3) in 1 step I would swap (1,5) to create (5,4,2,1,3,3). In step 2 I would swap (2,3) to create (5,4,3,1,3,2). If after the n < k(th) point we already have the largest permutation e.g. (5,4,3,3,2,1) then we stop.
So far this is what I have:
x<-y<-c(1,4,2,5,3,3)
sx<-sort(x,decreasing=TRUE)
if(k>=n){cat(sx)} else{ ### If we have more operations than numbers?
i<-0; k<-2
m<-max(y)
while(i<k){
if(all(sort(x,decreasing=TRUE)==y)){break}
i<-i+1
a<-max(which(y==m))
while(length(which(y[c(1:a)]<m))==0){
m<-m-1
a<-which(y==m) ### Location of the largest number
if(length(a)==0){
a<-1
next
}
a<-max(a)
}
y[c(min(which(y[c(1:a)]<m)),a)]<-y[c(a,min(which(y[c(1:a)]<m)))]
}
cat(y)
}
5 4 2 1 3 3
Essentially the code finds the max of the current set. Then finds the right most occurrence of this max number. Then finds the left most number lower than the max number. Then switches them. This continues until we have performed k steps OR we have the largest permutation before k. Then prints it.
This code works but takes too long if there are more than 10^4 digits for large k. Is there a way to reduce complexity to O(n) in R?
Here's an O(n log n)-time algorithm (O(n) is impossible with comparisons only, though maybe you know something about the input numbers).
For each subarray of the permutation having (zero-indexed) bounds [i 2^j, (i+1) 2^j) for some integers i, j, store the minimum and the maximum value in the subarray (i.e., set up a segment tree structure).
To find the maximum in an interval in time O(log n), decompose the interval into O(log n) elementary intervals and return the maximum of the maximums.
To find the rightmost maximum in an elementary interval in time O(log n), repeatedly descend to the right child if its maximum is equal to the target, else descend to the left child.
To find the leftmost number lower than a target number in an interval in time O(log n), decompose the interval into O(log n) elementary intervals and find the leftmost elementary interval whose minimum is lower than the target. From this interval, repeatedly descend to the left child if its minimum is lower than the target, else the descend to the right child.
Following your example:
1,5
4,5 1,2 3,3
5 4 2 1 3 3
We just moved 5, and 4 is in the right place, so we want the maximum on the rest of the array. The elementary intervals are 2 1 and 3 3. The maximum is 3. We examine 3 3 and discover that the maximum is in the right child, all the way at the end.
Now we seek the leftmost number less than 3. The elementary intervals are 2 1 and 3 3. We see that 2 1 has a minimum less than 3, so we examine it. So does the left child of 2 1, so 2 is what we swap 3 with.
*1,5*
4,5 *1,2* *3,3*
5 4 3 1 3 2
The aggregates in *asterisks* may need updating (ancestors of the swapped values). There are O(log n) of these. We work bottom up.
*1,5*
4,5 1,3 *3,3*
5 4 3 1 3 2
1,5
4,5 1,3 *3,3*
5 4 3 1 3 2
1,5
4,5 1,3 2,3
5 4 3 1 3 2

Is there a closed form available for the following table?

Below is a table which has a recursive relation as current cell value is the sum of the upper and left cell.
I want to find the odd positions for any given row denoted by v(x) as represented in the first column.
Currently, I am maintaining two one arrays which I update with new sum values and literally checking if each positions value is odd or even.
Is there a closed form that exists which would allow me to directly say what are the odd positions available (say, for the 4th row, in which case it should tell me that p1 and p4 are the odd places).
Since it is following a particular pattern I feel very certain that a closed form should exist which would mathematically tell me the positions rather than calculating each value and checking it.
The numbers that you're looking at are the numbers in Pascal's triangle, just rotated ninety degrees. You more typically see it written out like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
...
You're cutting Pascal's triangle along diagonal stripes going down the left (or right, depending on your perspective) strips, and the question you're asking is how to find the positions of the odd numbers in each stripe.
There's a mathematical result called Lucas's theorem which is useful for determining whether a given entry in Pascal's triangle is even or odd. The entry in row m, column n of Pascal's triangle is given by (m choose n), and Lucas's theorem says that (m choose n) mod 2 (1 if the number is odd, 0 otherwise) can be found by comparing the bits of m and n. If n has a bit that's set in a position where m doesn't have that bit set, then (m choose n) is even. Otherwise, (m choose n) is odd.
As an example, let's try (5 choose 3). The bits in 5 are 101. The bits in 3 are 011. Since the 2's bit of 3 is set and the 2's bit of 5 is not set, the quantity (5 choose 3) should be even. And since (5 choose 3) = 10, we see that this is indeed the case!
In pseudocode using relational operators, you essentially want the following:
if ((~m & n) != 0) {
// Row m, entry n is even
} else {
// Row m, entry n is odd.
}

F#: integer (%) integer - Is Calculated How?

So in my text book there is this example of a recursive function using f#
let rec gcd = function
| (0,n) -> n
| (m,n) -> gcd(n % m,m);;
with this function my text book gives the example by executing:
gcd(36,116);;
and since the m = 36 and not 0 then it ofcourse goes for the second clause like this:
gcd(116 % 36,36)
gcd(8,36)
gcd(36 % 8,8)
gcd(4,8)
gcd(8 % 4,4)
gcd(0,4)
and now hits the first clause stating this entire thing is = 4.
What i don't get is this (%)percentage sign/operator or whatever it is called in this connection. for an instance i don't get how
116 % 36 = 8
I have turned this so many times in my head now and I can't figure how this can turn into 8?
I know this is probably a silly question for those of you who knows this but I would very much appreciate your help the same.
% is a questionable version of modulo, which is the remainder of an integer division.
In the positive, you can think of % as the remainder of the division. See for example Wikipedia on Euclidean Divison. Consider 9 % 4: 4 fits into 9 twice. But two times four is only eight. Thus, there is a remainder of one.
If there are negative operands, % effectively ignores the signs to calculate the remainder and then uses the sign of the dividend as the sign of the result. This corresponds to the remainder of an integer division that rounds to zero, i.e. -2 / 3 = 0.
This is a mathematically unusual definition of division and remainder that has some bad properties. Normally, when calculating modulo n, adding or subtracting n on the input has no effect. Not so for this operator: 2 % 3 is not equal to (2 - 3) % 3.
I usually have the following defined to get useful remainders when there are negative operands:
/// Euclidean remainder, the proper modulo operation
let inline (%!) a b = (a % b + b) % b
So far, this operator was valid for all cases I have encountered where a modulo was needed, while the raw % repeatedly wasn't. For example:
When filling rows and columns from a single index, you could calculate rowNumber = index / nCols and colNumber = index % nCols. But if index and colNumber can be negative, this mapping becomes invalid, while Euclidean division and remainder remain valid.
If you want to normalize an angle to (0, 2pi), angle %! (2. * System.Math.PI) does the job, while the "normal" % might give you a headache.
Because
116 / 36 = 3
116 - (3*36) = 8
Basically, the % operator, known as the modulo operator will divide a number by other and give the rest if it can't divide any longer. Usually, the first time you would use it to understand it would be if you want to see if a number is even or odd by doing something like this in f#
let firstUsageModulo = 55 %2 =0 // false because leaves 1 not 0
When it leaves 8 the first time means that it divided you 116 with 36 and the closest integer was 8 to give.
Just to help you in future with similar problems: in IDEs such as Xamarin Studio and Visual Studio, if you hover the mouse cursor over an operator such as % you should get a tooltip, thus:
Module operator tool tip
Even if you don't understand the tool tip directly, it'll give you something to google.

Subtract / Divide two lists of digits

I want to represent numbers as lists of digits. How can I add subtract and divide the two numbers even if they are of different size ?
For example : 100 - 12 = 88 is equivalent to (1 0 0 ) minus ( 1 2) = ( 8 8)
100 / 12 = 8 is equivalent to (1 0 0 ) divided by (1 2 ) = (8)
There are two ways to represent numbers as digits in decimal. Lets imagine I want to represent the number 123. One obvious one is to do it from most significant digit to least like (1 2 3). Thats good for presentation only. The other way is to do it least to most significant (3 2 1).
When adding and substracting you add from the least significant digits and if the sum is above 9 you carry (add 1 to the next digit in one of the numbers) and continue recursing.
So do you know how to long add? If so this will be a piece of cake to do. 123 + 49 is (+ '(9 4) '(3 2 1)) ; ==> (2 7 1). Good luck!

Why we need to add 1 while doing 2's complement

The 2's complement of a number which is represented by N bits is 2^N-number.
For example: if number is 7 (0111) and i'm representing it using 4 bits then, 2's complement of it would be (2^N-number) i.e. (2^4 -7)=9(1001)
7==> 0111
1's compliment of 7==> 1000
1000
+ 1
-------------
1001 =====> (9)
While calculating 2's complement of a number, we do following steps:
1. do one's complement of the number
2. Add one to the result of step 1.
I understand that we need to do one's complement of the number because we are doing a negation operation. But why do we add the 1?
This might be a silly question but I'm having a hard time understanding the logic. To explain with above example (for number 7), we do one's complement and get -7 and then add +1, so -7+1=-6, but still we are getting the correct answer i.e. +9
Your error is in "we do one's compliment and get -7". To see why this is wrong, take the one's complement of 7 and add 7 to it. If it's -7, you should get zero because -7 + 7 = 0. You won't.
The one's complement of 7 was 1000. Add 7 to that, and you get 1111. Definitely not zero. You need to add one more to it to get zero!
The negative of a number is the number you need to add to it to get zero.
If you add 1 to ...11111, you get zero. Thus -1 is represented as all 1 bits.
If you add a number, say x, to its 1's complement ~x, you get all 1 bits.
Thus:
~x + x = -1
Add 1 to both sides:
~x + x + 1 = 0
Subtract x from both sides:
~x + 1 = -x
The +1 is added so that the carry over in the technique is taken care of.
Take the 7 and -7 example.
If you represent 7 as 00000111
In order to find -7:
Invert all bits and add one
11111000 -> 11111001
Now you can add following standard math rules:
00000111
+ 11111001
-----------
00000000
For the computer this operation is relatively easy, as it involves basically comparing bit by bit and carrying one.
If instead you represented -7 as 10000111, this won't make sense:
00000111
+ 10000111
-----------
10001110 (-14)
To add them, you will involve more complex rules like analyzing the first bit, and transforming the values.
A more detailed explanation can be found here.
Short answer: If you don't add 1 then you have two different representations of the number 0.
Longer answer: In one's complement
the values from 0000 to 0111 represent the numbers from 0 to 7
the values from 1111 to 1000 represent the numbers from 0 to -7
since their inverses are 0000 and 0111.
There is the problem, now you have 2 different ways of writing the same number, both 0000 and 1111 represent 0.
If you add 1 to these inverses they become 0001 and 1000 and represent the numbers from -1 to -8 therefore you avoid duplicates.
I'm going to directly answer what the title is asking (sorry the details aren't as general to everyone as understanding where flipping bits + adding one comes from).
First let motivate two's complement by recalling the fact that we can carry out standard (elementary school) arithmetic with them (i.e. adding the digits and doing the carrying over etc). Easy of computation is what motivates this representation (I assume it means we only 1 piece of hardware to do addition rather than 2 if we implemented subtraction differently than addition, and we do and subtract differently in elementary school addition btw).
Now recall the meaning of each of the digit's in two's complements and some binary numbers in this form as an example (slides borrowed from MIT's 6.004 course):
Now notice that arithmetic works as normal here and the sign is included inside the binary number in two's complement itself. In particular notice that:
1111....1111 + 0000....1 = 000....000
i.e.
-1 + 1 = 0
Using this fact let's try to derive what the two complement representation for -A should be. So the problem to solve is:
Q: Given the two's complement representation for A what is the two's complement's representation for -A?
To do this let's do some algebra using values we know:
A + (-A) = 0 = 1 + (-1) = 11...1 + 00000...1 = 000...0
now let's make -A the subject expressed in terms of numbers expressed in two's complement:
-A = 1 + (-1 - A) = 000.....1 + (111....1 - A)
where A is in two's complements. So what we need to compute is the subtraction of -1 and A in two's complement format. For that we notice how numbers are represented as a linear combination of it's bases (i.e. 2^i):
1*-2^N-1 + 1 * 2^N-1 + ... 1 = -1
a_N * -2^N-1 + a_N-1 * 2^N-1 + ... + a_0 = A
--------------------------------------------- (subtract them)
a_N-1 * -2^N-1 + a_N-1 -1 * 2^N-1 + ... + a_0 -1 = A
which essentially means we subtract each digit for it's corresponding value. This ends up simply flipping bits which results in the following:
-A = 1 + (-1 - A) = 1 + ~ A
where ~ is bit flip. This is why you need to bit flip and add 1.
Remark:
I think a comment that was helpful to me is that complement is similar to inverse but instead of giving 0 it gives 2^N (by definition) e.g. with 3 bits for the number A we want A+~A=2^N so 010 + 110 = 1000 = 8 which is 2^3. At least that clarifies what the word "complement" is suppose to mean here as it't not just the inverting of the meaning of 0 and 1.
If you've forgotten what two's complement is perhaps this will be helpful: What is “2's Complement”?
Cornell's answer that I hope to read at some point: https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html#whyworks

Resources