Java modulus operator - java

Use a modulus operator is something which all programmers must to know. I know it =).
In java we have :
int a = 100 , b = 50, c;
If we do :
c = a % b; // c = 0 because : 100 = 50*2 + 0 | D = d*q + r using simple maths
However I felt a little frustrated for not finding the Why of this operation :
c = b % a; // c = 50 ???? It seems not to have logic when a use D = d*q + r
Can someone could explain me why 50 % 100 is 50 ??? I can't understand very well.
Thanks

Becuase you can multiply by 0:
c = 100*0 + 50;
It's the + 50 that is returned as modulo.

Think of it this way:
100 goes into 50 how many times?
Zero times. So there must be 50 left over. Therefore the answer is 50.

Related

Weird Java Syntax

I was doing a practice Computer Science UIL test form when I came across this problem:
What is output by the following?
int a = 5;
int b = 7;
int c = 10;
c = b+++-c--+--a;
System.out.println(a + " " + b + " " + c);
I put down the answer "No output due to syntax error" but I got it wrong. The real answer was 4 8 1! (I tested it out myself)
Can someone please explain to me how line 4 works?
Thanks
I added some parentheses:
int a = 5;
int b = 7;
int c = 10;
c = (b++) + (-(c--)) + (--a);
System.out.println(a + " " + b + " " + c);
b++ :
b = b + 1 after b is used
c-- :
c = c - 1 after c is used
--a :
a = a - 1 before a is used
Look at it like this:
(b++) + (-(c--)) + (--a)
That should make more sense!
Look at Operator Precedence to see why it works this way.
Look at initialization of c like this, c = (b++) + (-(c--)) + (--a);
They had it compressed and intentionally confusing for your learning purposes. The code is essentially saying this, c = (b + 1) + (-(c - 1)) + (a - 1);
Break up the statement a bit. It's intentionally obfuscated.
c = b++ + -c-- + --a;
What this means:
The variable c is assigned the result of...
b (incrementation will take effect after this line), plus
the unary operation - of c (decrementation will take effect after this line), plus
a (decrementation takes immediate effect).
Replace the variables with the values, and you get:
c = 7 + (-10) + 4
c = 1
...and the result of your print statement should be:
4 8 0
Let's slow down, and look hard at the equation. Think about this carefully.
int a = 5;
int b = 7;
int c = 10;
c = b+++-c--+--a;
b++ means increment b after assignment, so b stays equal to its original value in the equation, but will be incremented afterward the equation.
Then there's a +.
Then a negated c--. c gets decremented but will remain the same for the equation.
Then add that to --a, which means a gets decremented immediately.
So the variables values at the print statement will be:
c = 7 + -10 + 4 = 1
a = 4
b = 8
May I add that in my opinion this is a bad question for a test. All its really asking is if you understand i++ vs ++i.

Linear Recurrence for very large n

I was trying to solve this problem on SPOJ (http://www.spoj.pl/problems/REC/)
F(n) = a*F(n-1) + b where we have to find F(n) Mod (m)
where
0 <= a, b, n <= 10^100
1 <= M <= 100000
F(0)=1
I am trying to solve it with BigInteger in JAVA but if I run a loop from 0 to n its getting TLE. How could I solve this problem? Can anyone give some hint? Don't post the solution. I want hint on how to solve it efficiently.
Note that the pattern of residues mod (m) should have a repeating pattern in a linear recurrence, and with length <= m by the pigeonhole principle. You need only calculate the first m entries, then figure out which of those entries will apply to F(n) for the actual value of n.
It also helps to solve a simpler problem. Let's pick really small values, say a=2, b=1, m=5, n=1000.
F(0) = 1
F(1) = 2*F(0) + 1 = 2*1 + 1 = 3 -> 3 Mod 5 = 3
F(2) = 2*F(1) + 1 = 2*3 + 1 = 7 -> 7 Mod 5 = 2
F(3) = 2*F(2) + 1 = 2*7 + 1 = 15 -> 15 Mod 5 = 0
F(4) = 2*F(3) + 1 = 2*15 + 1 = 31 -> 31 Mod 5 = 1
F(5) = 2*F(4) + 1 = 2*31 + 1 = 63 -> 63 Mod 5 = 3
etc.
Notice that the residues are [1, 3, 2, 0, 1, 3, ...], which will repeat forever. So from this example, how would you determine F(1000) Mod 5 without looping all the way to the 1000th entry?
First, I'll tell you how to solve a simpler problem. Suppose that b is zero. Then you just need to calculate an mod M. Instead of multiplying n-1 times, use a divide-and-conquer technique:
// Requires n >= 0 and M > 0.
int modularPower(int a, int n, int M) {
if (n == 0)
return 1;
int result = modularPower(a, n / 2, M);
result = (result * result) % M;
if (n % 2 != 0)
result = (result * a) % M;
return result;
}
So you can calculate an in terms of afloor(n/2), then square that, and multiply by a again if n is odd.
To solve your problem, first define the function f(x) = (a x + b) (mod M). You need to calculate fn(1), which is applying f n times to the initial value 1. So you can use divide-and-conquer like the previous problem. Luckily, the composition of two linear functions is also linear. You can represent a linear function by three integers (the two constants and the modulus). Write a function that takes a linear function and an exponent and returns the function composed that many times.

BIlling system - Programming

I require some input on the below logic.
It is kind of billing system takes the input and has a value associated with it.
A = 2 , 3A = 5
B = 3
C = 1 , 4C = 3
My code , should be such that take ABCCBAACCA , output should be value which is 16.
My solution as of now, I m thinking to count every element in the string, and them mod(modulus) by 3 for A , 4 for C (as in the above case, no need in case of B) every element in order to get the result.
I'm confused what data structure I should be using in order to implement such system.
In pseudocode I believe it would be:
Count all A's, B's and C's
Divide A's by 3 and multiply by 5
Modulo A's by 3 and multiply by 2
Multiply B's by 3
Divide C's by 4 and multiply by 3
Modulo C's by 4
Sum the 5 results.
In Ruby it could like something like this:
input = "ABCCBAACCA"
letters = ["A", "B", "C"]
total = 0
def score(letter,count)
if letter == "A"
((count/3)*5)+((count%3)*2)
elsif letter == "B"
count*3
else letter == "C"
((count/4)*3)+(count%4)
end
end
letters.each do |letter|
puts "#{letter}: #{score(letter, input.count(letter))}"
total += score(letter, input.count(letter))
end
puts "Total: #{total}"
Which produces:
A: 7
B: 6
C: 3
Total: 16
Well, the modulus operator won't help you since you will be getting 0 everytime is a multiple of 3 or 5, depending the letter you are evaluating (if thats what you trying to describe, sorry if i got it wrong).
I believe the easiest way is scanning the string and just adding the values.
When you encounter a third A you just add 1, instead of 2 (because you have to subtract 4, then add 5)
Similarly with C, you just add 0, instead of 1, when you encounter the fourth C.
You need 2 additional variables to keep the instances of A and C, and yes, you can use modulus operator to know if you just arrived to a multiple where you have to add either 1 or 0, depending the case.
Hope this helps a bit.
EDIT:
Here, I did a quick implementation. Feel free to optimize it if you really need it ;)
String value = "ABCCBAACCA";
int numA =0;
int numC =0;
int endResult = 0;
for (int x = 0; x < value.length(); x++)
{
if (value.charAt(x) =='A')
{
numA = numA +1;
endResult = endResult + ((numA%3 == 0)?1:2);
}
else if (value.charAt(x) =='B')
{
endResult = endResult +3;
}
else if (value.charAt(x) =='C')
{
numC = numC +1;
endResult = endResult + ((numC%4 == 0)?0:1);
}
}
System.out.println(endResult); //16 as expected
class CharBucket
attr_accessor :count
def initialize(thresholds)
#thresholds = thresholds
#count = 0
end
def total
#thresholds.inject([0, #count]) do |sum_left, a|
sum = sum_left[0]
left = sum_left[1]
sum += (left / a[0]) * a[1]
left %= a[0]
[sum, left]
end[0]
end
end
a = CharBucket.new({3 => 5, 1 => 2})
b = CharBucket.new({1 => 3})
c = CharBucket.new({4 => 3, 1 => 1})
buckets = {'A' => a, 'B' => b, 'C' => c}
"ABCCBAACCA".each_char{|c| buckets[c].count += 1 }
total = buckets.values.inject(0){|sum, b| sum += b.total} # => 16
Well, I would start with something like this:
public static void main(String[] args) {
// FIXME
String inputString = null;
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (Character c : inputString.toCharArray()) {
map = countCharacters(map, c);
}
}
private static Map<Character, Integer> countCharacters(Map<Character, Integer> map,
Character charatcer) {
map.put(charatcer,
(map.get(charatcer) != null) ? map.get(charatcer) + 1 :
Integer.valueOf(1));
return map;
}
and then introduce #vlasits steps from second to 5th, as this code above is first step in his pseudocode. It counts all characters in your string by making map of "character" : "its Occurences", if there was no such a character before, it puts 1 to the map.

Algorithm for the each item

Product A costs $10 , B costs $3 and C costs $0.50.
A person bought 100 items for $100. How many of each item did the person buy.
I found the answer as-
94 * 0.5 = 47
1 * 3 = 3
5 * 10 = 50
But I am not able to implement it in java as the solution I got the result from Hit and Trial.
What will be the algorithm for solving this problem
Plain brute-force:
for (int i1 = 0; i1 <= 10; i1++) {
for (int i2 = 0; i2 < 34; i2++) {
int i3 = 100 - i2 - i1;
int total = i1 * 10 + i2 * 3 + i3 / 2;
if (total == 100 && i3 % 2 == 0)
System.out.println(i1 + " * 10 + " + i2
+ " * 3 + " + i3 + " * 0.5 = 100");
}
}
Gives two answers:
0 * 10 + 20 * 3 + 80 * 0.5 = 100
5 * 10 + 1 * 3 + 94 * 0.5 = 100
P.S. of course, it's not the optimal solution, but for just three items and 100 total amount - it's fine (and optimal from the point of time required to code it).
You need to implement your algorithm for solving these two equations
A + B + C = 100 -----------(1)
10A + 3B + 0.5C = 100 -----------(2)
From(2), we can figure out that:
C = 100 - A - B
Substitue this information in (2)
10A + 3B + 0.5 * ( 100 - A - B) = 100
This reduces to
19A + 5B = 100
Then you can deduct that:
B = 20 - (19A/5)
Now,try to find out (using an int loop) for what "whole" value of A, will B become a whole value ( as normally in such problems, you always buy whole commodities -like fruits no fractions)
You will find that when A=5, B=1.
Keep solving the equation this way, and replace A, B and C with Java variables and you will be able to proivide a solution.
Both solutions can be found very easily. ring bearer already gave almost the entire way of doing this. ring bearer ended with:
B = 20 - (19A/5)
We know something else, though:
A, B, and C are all non-negative integer values.
This means 19A/5 has to be (1) an integer (else B would not be an integer), and (2) at most 20 (else B would be negative). This means for (1), that A has to be a multiple of 5, and for (2), that A has to be at most 5.
Also note that the requirement 19A/5 <= 20 can be rewritten as:
19A <= 100
There are only two values for A that satisfy this: 0 and 5. A very fast way to find all solutions then would be to do something like:
for (A = 0; 19*A <= 100; A += 5)
{
// Show the solution for this value of A (with B = 20 - 19A/5 and C = 100 - A - B).
}
This is a variant of the knapsack problem and you can look for a dynamic-programming based solution, which cab be better than brute force (in terms of computational complexity). A simple search yielded links like this

Combining c = c & (1 << bit) and int c = passkey.charAt(i % passkey.length() in a Challenge

I'm breaking my head over this :
for(i=0; i<message.length(); i++) {
int c = passkey.charAt(i % passkey.length());
int d = message.charAt(i);
c = c & (1 << bit);
result = result + (char)(c ^ d);
}
I know that LyJwNh9iPil3 (message) translates to ENCRYPTED (result). What I can't figure out, is what the used passkey should be. Currently, I'm stuck at :
L = 76
E = 69
so result char = 69, so c must be 69^(1/76) = 1,05729... But that is AFTER the x-th few bits are chewed off, and after the division by the password length.
I believe I will never be able to solve this, the path I'm going. Can you confirm that? The number of letters in the message and the result is different, right?
You are wrong here:
69^(1/76) = 1,05729..
^ is bitwise XOR, not power.

Categories

Resources