One of the basics of Computer Science is knowing how numbers are represented in 2’s complement. Imagine that you write down all numbers between A and B inclusive in 2’s complement representation using 32 bits. How many 1’s will you write down in all ?
Input:
The first line contains the number of test cases T (<=1000). Each of the next T lines contains two integers A and B.
Output:
Output T lines, one corresponding to each test case.
Constraints:
-2^31 <= A <= B <= 2^31 - 1
Sample Input:
-2 0
-3 4
-1 4
Sample Output:
63
99
37
Explanation:
For the first case, -2 contains 31 1’s followed by a 0, -1 contains 32 1’s and 0 contains 0 1’s. Thus the total is 63.
For the second case, the answer is 31 + 31 + 32 + 0 + 1 + 1 + 2 + 1 = 99
for (int i=1; i<line[0]; i++)
{
int numOf1s = 0;
for (int j=line[i].A; j<=line[i].B; j++)
{
for (unsigned int n=j; n>0; n>>=1)
numOf1s += n & 1;
}
printf("%d\n",numOf1s);
}
Related
I hope I'm not making a stupid question but, I can't find any good explanation on this result:
35 % 36 is equal to 35
https://www.google.com.ph/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=35%20%25%2036
But if I divide the two numbers, 35 / 36 the result is: 0.97222222222 where I assume that the remainder would be 97.
Can anyone explain this?
When we divide 13 % 3 it gives 1 (the remainder)
similarly when we do 35 % 36 it will give the first number as remainder, as the dividend is less than the divider.
when you are dividing 35/36, integer division will give you 0 quotient.
Float division will give you the fraction value, and the fraction value is the remainder part.
13/3 = 4.33333 = 4 * 3 + (0.333)* 3
=(integer quotient) divider + remainder.
The result of 35 % 36 is equivalent to dividing 35 by 36, and returning the remainder. Since 36 goes into 35 exactly 0 times, you're left with a remainder of 35.
Similarly, let's assume you do 7 % 3. In this example, 3 goes into 7 twice and you're left with a remainder of 1. So 7 % 3 == 1.
I don't have the source code for the operation, but you could mimic it (I'm sure this isn't as efficient as whatever's built in!) with a small function like this:
public static class MyMath
{
public static int Mod(this int operand1, int operand2)
{
while (operand1 >= operand2)
operand1 -= operand2;
return operand1;
}
}
And then call it like this:
var remainder1 = 7.Mod(3); // 1
var remainder2 = 35.Mod(36); // 35
mod gives you the reminder of an integer division. 36 fits 0 times in 35 so
35 / 36 is 0 and has a reminder of 35 which is the result of mod
int i=1;
do
{
if (i % 13 == 0)
Response.Write(i + "<br>");
i++;
} while (i < 201);
as title, I want to print out the numbers that can be divisible by 13 from 1 to 200
The code above works, but why can't I write it this way?
int i=1;
do
{
Response.Write(i + "<br>");
i++;
} while (i < 201 && i % 13 = 0);
Thanks a lot!
Two loops are not the same. One of them continues as long as i < 201.Other one stops at the first number that can't be divided to 13.
In the second version, your while loop is using i % 13 == 0 as a part of the test for whether the while loop should even continue. So as soon as a number is not divisible by 13, the loop will stop.
The key here is that there are two different tests:
- the loop should continue as long as the number is not over 200
- a particular number should be printed if it is divisible by 13
So no arrangement that combines these into one test will be able to achieve the goal.
Like the title, I don't understand why that expression is always true?
Here is the detail:
// x, y, z, t is always different with each other
int x = 1;
int y = 2;
int z = 3;
int total = (int)Math.Pow(2, x) + (int)Math.Pow(2, y) + (int)Math.Pow(2, z);
int t = 4; // or any number which is not x, y, z
int result = (int)Math.Pow(2, t) & total;
result is always = 0
Can someone explain it please?
Here is some example how to apply this expression into my code :P.
I have list of day of week. I want to pick a day to go out with my friend. If today is not picked, ill not go anywhere :D
Some pre-defined value:
Day: Mon-Tue-Wed-Thu-Fri-Sat-Sun
Value: 1-2-3-4-5-6-7
I will pick Mon, Tue and Fri save value into my DB.
Instead of saving {1, 2, 5}, ill save 38 (2^1 + 2^2 + 2^5).
If today is Tue, I will check like this: 2^2 & 38 = 4. 4 is # 0 so today is the day, go out.
If today is Wed, I will check like this: 2^3 & 38 = 0. So today isn't, go to bed
To really understand what is happening here, you must first understand binary, because what you're doing with the & is a bitwise-and.
So, in our normal way of writing numbers, we use the decimal system, or base-10, system. You count from 0 to 9 and then prepend another number to indicate an "overflow": 10. In binary, or base-2, we can only count 0 or 1, before we must prepend another number. So, to count from 0 to 4 for example, we have binary: 0 = 0, 1 = 1, 2 = 10, 3 = 11, 4 = 100. Each one of these zeros or ones are bits, which are easy for a computer to calculate with since it can represent them as a transistor switching either on or off.
What you're doing here is generating numbers that are basically 1's with a lot of zeros in binary. You'll notice that if you do 10^x (Math.Pow(10, x)) you get multiples of 10 with a lot of zeros: 10, 100, 1000, 10000, etc.
2^x (Math.Pow(2, x)) does the same thing: it generates the binary numbers 1, 10, 100, 1000, 10000. In our decimal notation those binary numbers translate to 1, 2, 4, 8, 16 respectively.
Now what the & (bitwise AND) does, is return the binary code in which all the ones on the left are also one the right. So, say you have binary: 2^1 + 2^2 + 2^3 = 1 + 10 + 100 = 111.
And you do a bitwise operation with 2^4 on the left, which is 1000. So you're asking if 1000 & 0111 (you can add as many zeros to the left of any binary code, just as you could with a decimal number: 00100 is still just one hundred). This evaluates to 0000 = 0.
You noticed that when t is either x, y, or z, it returns either x, y or z respectively, effectively acting like a filter, because, well: 0010 & 0111 = 0010 (there are both ONES in the second position). A more complex example would be 0110 1100 & 1100 0101 = 0100 0100.
There; now you can calculate your computer does :-)
If you see it as binary, and as long as x,y,z are distinct numbers, the result of;
(int)Math.Pow(2, x) + (int)Math.Pow(2, y) + (int)Math.Pow(2, z)
is an integer with bit x, y and z (and only those bits) set.
(int)Math.Pow(2, t) & total
...checks if bit t is set. As long as t is distinct from x, y, z, it won't be.
It's because:
total = 14
Math(2,4) = 16
16 and 14 = 0
it's binary operation!
16 = (10000) binary
14 = (01110) binary
no common bit between them so and will return 0. If you expected othere result maybe you wanted to do or?
16 or 14 = 30
Its a binary comparison (& compares each position in the two numbers and returns 1 if both are 1):
10000 // 16 in binary
01110 // 14 in binary
00000 // 14 & 16 = 0
Use some other value there instead, and you will get a different value. Take, for example 6 and 10:
00101 // 6 in binary
01110 // 14 in binary
00100 // 6 and 14 = 8
PS: You can experiment with this type of math using the calculator on your PC by choosing View > Programmer, and switching between Bin and Dec on the left hand side.
Think of x, y, z and t as bit positions - you're doing a bitwise & which will clear any bits which aren't set in both operands, and 2t will only have the tth bit set.
So if x, y and z are all different, 2x + 2y + 2z will have bits x, y andz set, and 2t will have bit t set... so performing a bitwise AND operation on the two results will always give 0.
Now your original claim (which didn't specify that x, y and z were different) isn't quite true, because if x and y are the same (for example) the addition can effectively give you a different bit. (Addition of integer values each of which has just a single bit set is only equivalent to bitwise-OR if the operands all have different bits set.)
For example:
int x = 2;
int y = 2;
int z = 10; // Ignore this, effectively
// 2^2 + 2^2 + 2^10 == 2^3 + 2^10
int total = (int)Math.Pow(2, x) + (int)Math.Pow(2, y) + (int)Math.Pow(2, z);
int t = 3;
int result = (int)Math.Pow(2, t) & total; // result is now 8
& Does binary AND operation and hence binary ADD of 16 and 14 is 0
10000
& 01110
-------
00000
total = 14
Math(2,4) = 16
So
(10000) // 16
(01110) // 14
(00000) // 16 & 14 = 0
(int)Math.Pow(2, t) = (2^4)base 10 = (10000)base 2
total = (2^3 + 2^2 + 2^1)base 10 = (01110)base 2
& is binary AND and can be considered as multiplication between every bits
therefore
1*0 = 0
0*1 = 0
0*1 = 0
0*1 = 0
0*0 = 0
(int)Math.Pow(2, t) & total = (10000)base 2 & (01110)base 2 = (00000)base 2 = 0
Assume we have
total1 = (10001)base 2
then
(int)Math.Pow(2, t) & total1 = (10000)base 2 & (10001)base 2 = (10000)base 2 = (16)base 10
Here you are doing a binary operation by using &.
This & is equal to bitwise AND (AND gate) . AND works like this.
When 1 & 1 =1
when 1 & 0 = 0
when 0 & 1 = 0
when 0 & 0 = 0
when matching values met it will output 1 , else it will output 0.Check how and works
1001
1110
------
1000
------
so value of binary 1000 is 8
When dealing with the C# shift operators, I encountered a unexpected behavior of the shift-left operator.
Then I tried this simple function:
for (int i = 5; i >= -10; i--) {
int s = 0x10 << i;
Debug.WriteLine(i.ToString().PadLeft(3) + " " + s.ToString("x8"));
}
With this result:
5 00000200
4 00000100
3 00000080
2 00000040
1 00000020
0 00000010
-1 00000000 -> 00000008 expected
-2 00000000 -> 00000004 expected
-3 00000000 -> 00000002 expected
-4 00000000 -> 00000001 expected
-5 80000000
-6 40000000
-7 20000000
-8 10000000
-9 08000000
-10 04000000
Until today, I expected that the << operator can deal with negative values of the second operand.
MSDN tells nothing about the behavior when using negative values of the second operand. But MSDN says that only the lower 5 bits (0-31) are used by the operator, which should fit for negative values.
I also tried with long values: long s = 0x10L << i;, but with the same result.
So what happens here?
EDIT
As stated in your answers, the negative value representation is not the reason for this.
I got the same wrong result for all cases:
0x10<<-3 = 0x00000000 (wrong!)
0x10<<(int)(0xfffffffd) = 0x00000000 (wrong!)
0x10<<(0x0000001d = 0x00000000 (wrong!)
expected = 0x00000002
EDIT #2
One of these two should be true:
1) The shift operator is a real shift-operator, so the results should be:
1a) 0x10 << -3 = 00000002
1b) 0x10 << -6 = 00000000
2) The shift operator is a rotate-operator, so the results should be:
2a) 0x10 << -3 = 00000002 (same as 1a)
2b) 0x10 << -6 = 40000000
But the shown results does not fit either to 1) nor to 2) !!!
Negative numbers are two complemented, so -1 == 0xFFFFFFFF, and 0xFFFFFFFF & 31 == 31, -2 == 0xFFFFFFFE, and 0xFFFFFFFE & 31 == 30 and so on.
-10 == 0xFFFFFFF6, and 0xFFFFFFF6 & 31 == 22, in fact:
(0x10 << 22) == 04000000
Some code to show:
const int num = 0x10;
int maxShift = 31;
for (int i = 5; i >= -10; i--)
{
int numShifted = num << i;
uint ui = (uint)i;
int uiWithMaxShift = (int)(ui & maxShift);
int numShifted2 = num << uiWithMaxShift;
Console.WriteLine("{0,3}: {1,8:x} {2,2} {3,8:x} {4,8:x} {5}",
i,
ui,
uiWithMaxShift,
numShifted,
numShifted2,
numShifted == numShifted2);
}
With long it's the same, but now instead of & 31 you have & 63. -1 == 63, -2 == 62 and -10 == 54
Some example code:
const long num = 0x10;
int maxShift = 63;
for (int i = 5; i >= -10; i--)
{
long numShifted = num << i;
uint ui = (uint)i;
int uiWithMaxShift = (int)(ui & maxShift);
long numShifted2 = num << uiWithMaxShift;
Console.WriteLine("{0,3}: {1,8:x} {2,2} {3,16:x} {4,16:x} {5}",
i,
ui,
uiWithMaxShift,
numShifted,
numShifted2,
numShifted == numShifted2);
}
Just to be clear:
(int x) << y == (int x) << (int)(((uint)y) & 31)
(long x) << y == (long x) << (int)(((uint)y) & 63)
and not
(int x) << y == (int x) << (Math.Abs(y) & 63)
(long x) << y == (long x) << (Math.Abs(y) & 63)
And what you think "should be" "it would be beautiful if it was" "has to be" ecc is irrelevant. While 1 and 0 are "near" (their binary representation has a "distance" of 1 in number of different bits), 0 and -1 are "far" (their binary representation has a "distance" of 32 or 64 in number of different bits)
You think you should get this:
-1 00000000 -> 00000008 expected
-2 00000000 -> 00000004 expected
-3 00000000 -> 00000002 expected
-4 00000000 -> 00000001 expected
but in truth what you don't see is that you are getting this:
-1 (00000008) 00000000
-2 (00000004) 00000000
-3 (00000002) 00000000
-4 (00000001) 00000000
-5 (00000000) 80000000 <-- To show that "symmetry" and "order" still exist
-6 (00000000) 40000000 <-- To show that "symmetry" and "order" still exist
where the part in (...) is the part that is to the "left" of the int and that doesn't exist.
It has to do with the representation of negative numbers. -1 corresponds to all-ones, so its five least significant bits sum to 31 and left-shifting 0x10 by 31 bits gives all zeroes (the high-order bit that is already set is discarded as per the documentation).
Increasingly larger negative numbers correspond to shifting by 30, 29, etc bits. The bit that is already set in 0x10 is in zero-based position 4, so in order for it to not be discarded the shift has to be at most 31 - 4 = 27 bits, which happens when i == -5.
You can easily see what's going on if you try e.g. Console.WriteLine((-1).ToString("x8")):
ffffffff
Update: when first operand is a long you see similar behavior because now six least significant bits are counted from the second operand: 0x10L << -1 shifts left 63 bits, etc.
The left shift operator doesn't see a negative second operand as a right shift. It will just use the lower five bits of the value and make a left shift using that.
The lower five bits of the value -1 (0xFFFFFFFF) will be 31 (0x0000001F), so the first operand 0x10 is shifted to the left 31 steps leaving just the least significant bit in the most significant bit of the result.
In other words, 0x10 << -1 is the same as 0x10 << 31 which will be 0x800000000, but the result is just 32 bits so it will be truncated to 0x00000000.
When you are using a long value, the six least significant bits are used of the second operand. The value -1 becomes 63, and the bits are still shifted out outside the range of the long.
I've been looking into combinations lately, I've tried various 3rd party solutions, and tried to get my head around it myself. Without success I might add.
I need to generate a 13 length string with all possible combinations of say.. int 0-2, I.E
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 0 0 0 1 0
...
2 2 2 2 2 2 2 2 2 2 2 2 2
You probably get the drill, I'm aware I could just wrap this up in loops if I wanted a dirty solution. Any guidance or pointers are appreciated.
I'd be happy to write the code for you, but it seems like you are looking for intuition into the problem. So maybe this feels more like a "teach a man to fish" moment.
So let me ask you a few questions:
Let's generalize the problem to strings of length N. What does the N=1 case look like? It's
0
1
2
And what does the N=2 case look like? It's
00
01
02
10
11
12
20
21
22
I wonder if you can see how, given the N=1 case, we can easily derive (aka generate) the N=2 case in a very mechanical fashion. Now if you see the pattern for this specific case, can you say what the pattern is for the general case? i.e. If you happened to already have in your hand the answer for strings of length N, and I asked you to provide me with the answer for strings of length N+1 could you do so? If so you have the very definition of a recursive algorithm.
PS I think I'd call these combinations rather than permutations.
I can't help thinking of this as just adding number in a N-based numeric system (in your example a 3-base system).
I would write one method (if not already there in the framework or a library) that would allow you to switch bases. I.E:
String transformNumberFrom10BaseToXBase(int number, int base)
then just write a for loop (sorry, pseudo-c-like-code :) ):
for (int i = 0; i < base ^ 13; i++) {
print transformNumberFrom10BaseToXBase(i, base)
}
Ok, hope that helps or give you an idea on how to solve it :)
I've written quickly function that returns list of permutations, so if you have not time to write your own method, you can use it. length is permutation length, max is maximum number (in your case, it would be 2)
static List<int[]> getPermutationList(int length, int max)
{
List<int[]> perm_list = new List<int[]>();
int[] perm = new int[length];
for (int i = 0; i < length; ++i)
perm[i] = 0;
while(true)
{
for (int i = length - 1; ; --i)
{
if (i == -1)
return perm_list;
if (perm[i] < max)
{
perm[i]++;
for (int j = i + 1; j < length; ++j)
perm[j] = 0;
break;
}
}
int[] perm_copy = new int[length];
for (int i = 0; i < length; ++i)
{
perm_copy[i] = perm[i];
}
perm_list.Add(perm_copy);
}
return perm_list;
}