This is my first problem:
gcd(x,y)
if (x < y)
gcd(y,x)
else
if (y = 0)
return x
else
return gcd(y, x mod y)
This is my second problem:
public static int Test2(int x, int y) {
if (x > y) {
return 10;
} else {
return Test2(x-5, y+5) + 5;
}
}
The question is: What is returned for gcd(84, 21)?
a. 84
b. 21
c. 3 (This is the correct answer)
d. 10
X equals 84 and y equals 21. So I run them through the Algorithm class. 84 is not less than 21 so I skip that if statement. 84 is not equal so I skip that statement. I go to return gcd(y, x mod y). I don’t understand what is mod and how do you figure out what it means?
Second problem!
Question: What is returned for Test2(18,5)?
A. 5
B. 10
I choose ten , because x is greater than y and when processed to the if statement. It returns a value of ten. The if statements does run anything but the return statement.
C. 15 The answer is 15.
D. 20
mod is the modulo function. It's the rest when when you divide two integers. For example,
1 mod 3 = 1
2 mod 3 = 2
3 mod 3 = 0
4 mod 3 = 1
10 mod 4 = 2
10 is the correct answer for the second question, your argument is correct.
The modulo operator returns the remainder of a divison operation. e.g. 3 mod 2 = 1 since 1 is the remainder. % is commonly used as the symbol for mod. In this example 84 mod 21 equals 0 since 21 divides evenly into 84 four times.
x mod y is not valid Java, x % y is and it means modulo; that what if left after an integer division of x by y.
Btw, what do you mean with this is the answer and the answer is 15? Better to think the problem through and explain your own answer.
Related
I'm trying to solve this problem:
"2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
Please, do not tell me the answer, I really want to solve it by myself. All I need is an advice regarding math aspect of the question. The thing is adding one every cycle isn't a good idea because the process is too slow. Or is there a problem with variable type not being long?
I've tried to get number which is evenly divisible of all numbers between (1 and 10), and even (1 and 17), and the algorithm worked well.
int in_num = 1;
int score = 0;
public void calculate() {
while (true) {
score = 0;
for (int x = 1; x < 21; x++) {
if ((in_num%x) == 0) {
score++;
}
}
System.out.println("Number " + in_num + " has " + score );
if (score == 20) {
System.out.println(in_num);
break;
}
in_num++;
}
I expect the specific integer, but I get infinite loop.
Isn't this enough?
Multiply every prime number from 1 to 20 to get the number! Also instead of 2 use 16 and instead of 3 use 9.
Long number = 2 ^ 4 * 3 ^ 2 * 5 * 7 * 11 * 13 * 17 * 19L;
System.out.println(number);
Detailed Answer:
We need to find every prime number less than 20. After that, for each prime number, we must calculate the number to which we can exponentiate the prime number while it stays less than 20.
For example, if we multiply 2 four times with itself it remains below 20 (16). But if we calculate 2 to the fifth, it will be 32 which is greater than 20.
We will do the same for every other prime number. By this calculation the actual answer will be like this:
Long number = 2 ^ 4 * 3 ^ 2 * 5 ^ 1 * 7 ^ 1 * 11 ^ 1 * 13 ^ 1 * 17 ^ 1 * 19L ^ 1;
The lowest common multiple of two numbers x and y is xy/GCD(x,y), where GCD calculates the greatest common divisor.
You can implement GCD easily using Euclid's algorithm or the binary GCD algorithm: https://en.wikipedia.org/wiki/Greatest_common_divisor
The algorithm would be like:
result = 1;
for (x = 20; x > 0; --x)
result *= (x/GCD(x,result));
Of course this works for other numbers as well. If you really don't care about that, then you can just print 232792560
You are getting an infinite loop because of int (in_num) range exceeded its length; replace type int to Long (something bigger than int) you will not get any infinite loop and you will get your output.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a question. I need to solve this problem: 3 ^ 54 mod 17 =? (3 to 54 degrees modulo 17 - which will be equal to?). Just please write with the maximum explanation. How did you find this huge number 3 ^ 54, how to get the module. Thank you very much in advance!!!
Have a look at this two equivalent equations:
c mod m = (a ⋅ b) mod m
c mod m = [(a mod m) ⋅ (b mod m)] mod m
Knowing this you can compute 3 ^ 54 mod 17 very efficient:
3 ^ 54 mod 17 =
3 ^ 27 * 3 ^ 27 mod 17 =
(3 ^ 27 mod 17 * 3 ^ 27 mod 17) mod 17 =
...
Know we can calc the modulo very fast. But how can we divide c fast?
This can be handled by the idea of "Exponentiation by squaring".
x^n = x(x^2)^((n-1)/2) if n is odd
x^n = (x^2)^(n/2) if n is even
An algorithm that uses this techniques is called "Fast modular exponentiation"
int power(int x, int y, int p){
int res = 1;
x = x % p;
while (y > 0){
if (y % 2 == 0)
res = (res*x) % p;
y /= 2;
x = (x*x) % p;
}
return res;
}
We know that 3 and 17 are coprime (indeed, both are prime, but that's not required). Because of this, we know that 3 is a generate w.r.t. multiplication for the group of integers modulo 17. That is, for any value b between 1 and 16, inclusive, there is some a such that 3^a = b (mod 17). The only way that is possible is if 3^a gives unique values modulo 17 at least 16 times in a row (for 3^0, 3^1, ..., 3^15). Thus, it turns out that 3^16 = 1 (mod 17) and, generally, a^(b-1) = 1 (mod b) whenever a and b are coprime.
This observation will get you down to something with an exponent less than your modulus minus one. Again, it requires that the base and the modulus be coprime, but it's the case in your question and it is a case of interest typically speaking.
More generally, you can always just try multiplying the base by itself a number of times no greater than the modulus and you are bound to find a cycle. Determine the cycle length and offset in the cycle (if any) and you can work out something a lot like what we did above. For instance, if we have 2^103 = ? (mod 10), what can we do? We see 2, 2*2 = 4, 2*2*2 = 8, 2*2*2*2 = 16 = 6 (mod 10), 2*2*2*2*2 = 32 = 2 (mod 10; we have already hit a cycle so we know this repeats forever. Since 2^5 = 2^1 (mod 10), we can rewrite 2^103 as (2^5)^20 * 2^3 = 2^20 * 2^3 = (2^5)^4 * 2^3 = 2^4 * 2^ = 2^7 = 2^5 * 2^2 = 2 * 2^2 = 2^3 (mod 10), thus 8.
Finally, if you find a 0 as you're doing the above, just stop; the answer will be zero forever after. For instance, 2^102938210 = ??? (mod 8) has the answer 0 since we get 2^1 = 2, 2^2 = 4, 2^3 = 8 = 0 (mod 8).
I have been studying Java HashMap source code, the part of it which decides in what bucket to put an object and saw this change in Java 7 (8) as compared to Java 6.
Additionally I conducted numerous experiments and both expressions yeild the same result:
hash % n
and
hash & (n - 1)
where n - the array length that must be power of 2.
I just cannot figure out why is it true? Is there any theorem or some math laws that prove these statement are equal? Basically I want to understand the inference and prove the equivalence of those two statements.
PS. If n is not a power of 2 number, the equivalence breaks immedeately.
If n is a power of two that mean its binary representation is 10000....,
n-1 for that matter is 1111111... with one less digit.
That means that binary &-ing with (n-1) preserves just exactly the number of bits in k that n-1 has set.
Example n = 8: 1000, n-1 = 7: 111
&-ing for example k = 201: 11001001
k % n = k & (n-1) = 11001001 & 111 = 001 = 1.
%-ing with a power of 2 means that in binary you just strip everything away that is above (including) the only set bit: for n = 8 that means stripping everything over (including) the 4th bit. And that is exactly what the &-ing does at well.
A side effect is that using & is commutative: hash & (n - 1) is equivalent to (n - 1) & hash which is not true for %, the jdk source code in many places uses the later, e.g. in getNode
Think about the bits in (n - 1) if n is a power of 2 (or ((1 << i) - 1), if you want to simplify the constraint on n):
If n is, say, 16 (= 1 << 4), then n - 1 is 15, and the bit representation of 15 and 16 (as 32-bit ints) are:
1 = 00000000000000000000000000000001 // Shift by 4 to get...
16 = 00000000000000000000000000010000 // Subtract 1 to get...
15 = 00000000000000000000000000001111
So just the lowest 4 bits are set in 15. If you & this with another int, it will only allow bits in the last 4 bits of that number to be set in the result, so the value will only be in the range 0-15, so it's like doing % 16.
However, note that this equivalence doesn't hold for a negative first operand:
System.out.println(-1 % 2); // -1
System.out.println(-1 & (2-1)); // 1
Ideone demo
The arithmetic rule for integer / and % is:
x*(y/x) + (y%x) = y
What about a negative hash -4 and a positive n 8?
8*0 + (-4%8) = -4
Hence modulo maintains the sign.
-4 % 8 = -4
-4 & 7 = 4
Or:
int t = hash%n;
if (t < 0) {
t += n;
}
assert t == (hash & (n-1));
So in the earlier java with %n hash had to be positive to begin with.
Now hash may be negative, more solid and better hashing.
So that was a sound reason for this subtle change in java source code.
Background:
2n is a 1 followed by n-1 0s (in binary).
2n - 1 is n-1 1s.
Hence for n being a positive power of 2, and some positive number h:
h % n == h & (n-1)
Another usage is to count bits in an int. The class Integer has just such a function.
int bits = 0;
while (x != 0) {
x &= x - 1;
++bits;
}
I was trying to solve this question but the automated judge is returning "time limit exceeded" (TLE).
On the occasion of Valentine Day , Adam and Eve went on to take part in a competition.They cleared all rounds and got into the finals. In the final round, Adam is given a even number N and an integer K and he has to find the greatest odd number M less than N such that the sum of digits in binary representation of M is atmost K.
Input format:
For each test case you are given an even number N and an integer K
Output format:
For each test case, output the integer M if it exists, else print -1
Constraints:
1 ≤ T ≤ 104
2 ≤ N ≤ 109
0 ≤ K ≤ 30
Sample input:
2
10 2
6 1
Sample output:
9
1
This is what I have done so far.
static long play(long n, int k){
if(k==0) return -1;
if(k==1) return 1;
long m=n-1;
while(m>0){
long value=Long.bitCount(m); //built in function to count bits
if(value<=k ){
return m;
}
m=m-2;
}
return -1;
}
public void solve(InputReader in, OutputWriter out) {
long start=System.currentTimeMillis();
int t=in.readInt();
while(t-->0){
long n=in.readLong();
int k=in.readInt();
long result=play(n,k);
out.printLine(result);
}
long end=System.currentTimeMillis();
out.printLine((end-start)/1000d+"ms");
}
}
According to updated question N can be between 2 and 10^9. You're starting with N-1 and looping down by 2, so you get up to about 10^9 / 2 iterations of the loop. Not good.
Starting with M = N - 1 is good. And using bitCount(M) is good, to get started. If the initial bitcount is <= K you're done.
But if it's not, do not loop with step -2.
See the number in your mind as binary, e.g. 110101011. Bit count is 6. Let's say K is 4, that means you have to remove 2 bits. Right-most bit must stay on, and you want largest number, so clear the two second-last 1-bits. Result: 110100001.
Now, you figure out how to write that. And do it without converting to text.
Note: With N <= 10^9, it will fit in an int. No need for long.
You'll have to perform bitwise operations to compute the answer quickly. Let me give you a few hints.
The number 1 is the same in binary and decimal notation: 12 = 110
To make the number 102 = 210, shift 1 to the left by one position. In Java and many other languages, we can write this:
(1 << 1) == 2
To make the binary number 1002 = 410, shift 1 to the left by two positions:
(1 << 2) == 4
To make the binary number 10002 = 810 shift 1 to the left by three positions:
(1 << 3) == 8
You get the idea.
To see if a bit at a certain position is 1 or 0, use &, the bitwise AND operator. For example, we can determine that 510 = 1012 has a 1 at the third most significant bit, a 0 at the second most significant bit, and a 1 at the least significant bit:
5 & (1 << 2) != 0
5 & (1 << 1) == 0
5 & (1 << 0) != 0
To set a bit to 0, use ^, the bitwise XOR operator. For example, we can set the second most significant bit of 710 = 1112 to 0 and thus obtain 510 = 1012:
7 ^ (1 << 1) == 5
As the answer is odd,
let ans = 1, here we use 1 bit so k = k - 1;
Now binary representation of ans is
ans(binary) = 00000000000000000000000000000001
while(k > 0):
make 30th position set
ans(binary) = 01000000000000000000000000000001
if(ans(decimal) < N):
k -= 1
else:
reset 30th position
ans(binary) = 00000000000000000000000000000001
Do the same from 29th to 1st position
This question already has answers here:
Performing arithmetic operations in binary using only bitwise operators [duplicate]
(2 answers)
Closed 8 years ago.
I found some code to add two numbers using XOR and AND without using any arithmetical operators.
I understand that x^y equates to the sum and that x&y equates to the carry. However I don't understand why the carry must be left shifted? My knowledge of the left bitwise shift is that is the same as multiplying by two. Why is the carry being multiplied by two?
public static int add(int x, int y) {
// Iterate till there is no carry
while (y != 0)
{
// carry
int carry = x & y;
// Sum
x = x ^ y;
y = carry << 1;
}
return x;
}
Any guidance appreciated.
Lets try with two small integer x=5 which binary equivalent is 101 and y=1, which binary equivalent is 001.
Now, why I am talking about binary or more specifically, want to deal with bits? Because XOR is a bit wise operation.
So, if you run XOR operation between x and y, the result is following:
x = x^y = 101 ^ 001 = 100 (decimal :4)
See, just XOR operation between two numbers don't give us the sum. (sum of 5 and 1 should be 6, not 4) We use the carry, to get the exact sum. Actually, the algorithm is designed in a way, so that it gives us the correct answer.
Now, lets see, how using carry in this algorithm, gives us the correct answer.
Since,
carry = x & y = 101 & 001 = 1 (decimal 1)
According to your program, y = carry << 1;
So, y will now become = 001 << 1 = 010 (decimal :2)
The loop will keep running, until y becomes zero.
If you run the loop again (since y=2 and not zero)
x = x ^ y = 100 ^ 010 = 110 (decimal :6)
carry = x & y= 100 & 010 = 0 (decimal 0)
Now, the XOR between the new value of x and y is 6 which is exactly the sum of 5 and 1. Look at carry, its value is now 0.
Our y will also become 0 now, because right shifting 0 will also give us 0. Since y is now zero, the loop will not run anymore and we got our sum by returning x!