This question already has answers here:
Modulus division when first number is smaller than second number
(6 answers)
Closed 7 years ago.
I understand that a mod operator finds the remainder of two numbers. However, I am having trouble understanding the concept when the numbers are reversed. Meaning, a smaller number comes first in the operation.
int x = 4 % 3 ; // prints out 1
However, can someone explain this to me:
int y = 1 % 4 ; // prints out 1
int z = 2 % 3 ; // prints out 2
Thanks in advance!
Whether the left-hand side of the operator is larger than the right is irrelevant. There is always a remainder for any division operation, it's just that sometimes it's 0.
So 5 % 2 returns 1, just like 4 % 3 returns 1.
The value of any modulo operation of the form x % n will be 0 to n - 1 inclusive, for positive x. It will be -1(n-1) to 0 inclusive for negative x.
Are you sure about the int y that prints out 2?
The int z though seems normal :
2= 0*3 + 2
int y = 1 % 4 should print 1 because:
1=0*4 + 1
It works the same as when a bigger number comes first, you just take the remainder of the division of the first one by the second one.
Related
This question already has answers here:
How to add two numbers of any length in java?
(8 answers)
Closed 5 years ago.
Today I had an interview and the interviewer asked to make a program for addition of two numbers, I get shocked how can he give a simple question but the question is different
the length of two number can be anything (10,20,30 or even 1000 etc.)
if you convert it to int,double,long double if the number is greater than their range than the answer can be wrong.
Please help me for the question.
You can always take the two numbers in arrays (i.e. arrays have digits of the numbers as elements) and add them as we add manually i.e. start from one's digit and store the carry if it's present then do the same for ten's digit, then hundred's digit and so on.
Say you want to add 123 and 329.
X = 123, X[] = [1,2,3]
Y = 329, Y[] = [3,2,9]
You start with one's digit (the rightmost or last element) and add the elements of both X and Y arrays and add carry to it (initially set to 0). If the addition comes out to be greater than 10, set carry = sum / 10 (since we are adding each element, this carry shall always be either 0 or 1) and the addition to add [i] = sum % 10. Repeat till all the elements of smaller array are over. Then add the carry to remaining elements of larger array continuing the above logic.
carry = 0
Step 1 : 3 + 9 + carry (0) = 5, carry => 12 / 10 = 1, add => 12 % 10 = 2
Step 2 : 2 + 2 + carry (2) = 6, carry => 6 / 10 = 0, add => 6 % 10 = 6
Step 3 : 3 + 1 + carry (0) = 4, carry => 4 / 10 = 0, add => 4 % 10 = 4
Ans = 462
Obviously the array storing sum may have one digit extra so take care of that as well.
So this was a question on one of the challenges I came across in an online competition, a few days ago.
Question:
Accept two inputs.
A big number of N digits,
The number of questions Q to be asked.
In each of the question, you have to find if the number formed by the string between indices Li and Ri is divisible by 7 or not.
Input:
First line contains the number consisting on N digits. Next line contains Q, denoting the number of questions. Each of the next Q lines contains 2 integers Li and Ri.
Output:
For each question, print "YES" or "NO", if the number formed by the string between indices Li and Ri is divisible by 7.
Constraints:
1 ≤ N ≤ 105
1 ≤ Q ≤ 105
1 ≤ Li, Ri ≤ N
Sample Input:
357753
3
1 2
2 3
4 4
Sample Output:
YES
NO
YES
Explanation:
For the first query, number will be 35 which is clearly divisible by 7.
Time Limit: 1.0 sec for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
My Approach:
Now according to the constraints, the maximum length of the number i.e. N can be upto 105. This big a number cannot be fitted into a numeric data structure and I am pretty sure thats not the efficient way to go about it.
First Try:
I thought of this algorithm to apply the generic rules of division to each individual digit of the number. This would work to check divisibility amongst any two numbers, in linear time, i.e. O(N).
static String isDivisibleBy(String theIndexedNumber, int divisiblityNo){
int moduloValue = 0;
for(int i = 0; i < theIndexedNumber.length(); i++){
moduloValue = moduloValue * 10;
moduloValue += Character.getNumericValue(theIndexedNumber.charAt(i));
moduloValue %= divisiblityNo;
}
if(moduloValue == 0){
return "YES";
} else{
return "NO";
}
}
But in this case, the algorithm has to also loop through all the values of Q, which can also be upto 105.
Therefore, the time taken to solve the problem becomes O(Q.N) which can also be considered as Quadratic time. Hence, this crossed the given time limit and was not efficient.
Second Try:
After that didn't work, I tried searching for a divisibility rule of 7. All the ones I found, involved calculations based on each individual digit of the number. Hence, that would again result in a Linear time algorithm. And hence, combined with the number of Questions, it would amount to Quadratic Time, i.e. O(Q.N)
I did find one algorithm named Pohlman–Mass method of divisibility by 7, which suggested
Using quick alternating additions and subtractions: 42,341,530
-> 530 − 341 = 189 + 42 = 231 -> 23 − (1×2) = 21 YES
But all that did was, make the time 1/3rd Q.N, which didn't help much.
Am I missing something here? Can anyone help me find a way to solve this efficiently?
Also, is there a chance this is a Dynamic Programming problem?
There are two ways to go through this problem.
1: Dynamic Programming Approach
Let the input be array of digits A[N].
Let N[L,R] be number formed by digits L to R.
Let another array be M[N] where M[i] = N[1,i] mod 7.
So M[i+1] = ((M[i] * 10) mod 7 + A[i+1] mod 7) mod 7
Pre-calculate array M.
Now consider the expression.
N[1,R] = N[1,L-1] * 10R-L+1 + N[L,R]
implies (N[1,R] mod 7) = (N[1,L-1] mod 7 * (10R-L+1mod 7)) + (N[L,R] mod 7)
implies N[L,R] mod 7 = (M[R] - M[L-1] * (10R-L+1 mod 7)) mod 7
N[L,R] mod 7 gives your answer and can be calculated in O(1) as all values on right of expression are already there.
For 10R-L+1 mod 7, you can pre-calculate modulo 7 for all powers of 10.
Time Complexity :
Precalculation O(N)
Overall O(Q) + O(N)
2: Divide and Conquer Approach
Its a segment tree solution.
On each tree node you store the mod 7 for the number formed by digits in that node.
And the expression given in first approach can be used to find the mod 7 of parent by combining the mod 7 values of two children.
The time complexity of this solution will be O(Q log N) + O(N log N)
Basically you want to be able to to calculate the mod 7 of any digits given the mod of the number at any point.
What you can do is to;
record the modulo at each point O(N) for time and space. Uses up to 100 KB of memory.
take the modulo at the two points and determine how much subtracting the digits before the start would make e.g. O(N) time and space (once not per loop)
e.g. between 2 and 3 inclusive
357 % 7 = 0
3 % 7 = 3 and 300 % 7 = 6 (the distance between the start and end)
and 0 != 6 so the number is not a multiple of 7.
between 4 and 4 inclusive
3577 % 7 == 0
357 % 7 = 0 and 0 * 10 % 7 = 0
as 0 == 0 it is a multiple of 7.
You first build a list of digits modulo 7 for each number starting with 0 offset (like in your case, 0%7, 3%7, 35%7, 357%7...) then for each case of (a,b) grab digits[a-1] and digits[b], then multiply digits[b] by 1-3-2-6-4-5 sequence of 10^X modulo 7 defined by (1+b-a)%6 and compare. If these are equal, return YES, otherwise return NO. A pseudocode:
readString(big);
Array a=[0]; // initial value
Array tens=[1,3,2,6,4,5]; // quick multiplier lookup table
int d=0;
int l=big.length;
for (int i=0;i<l;i++) {
int c=((int)big[i])-48; // '0' -> 0, and "big" has characters
d=(3*d+c)%7;
a.push(d); // add to tail
}
readInt(q);
for (i=0;i<q;i++) {
readInt(li);
readInt(ri); // get question
int left=(a[li-1]*tens[(1+ri-li)%6])%7;
if (left==a[ri]) print("YES"); else print("NO");
}
A test example:
247761901
1
5 9
61901 % 7=0. Calculating:
a = [0 2 3 2 6 3 3 4 5 2]
li = 5
ri = 9
left=(a[5-1]*tens[(1+9-5)%6])%7 = (6*5)%7 = 30%7 = 2
a[ri]=2
Answer: YES
I can't figure out a proper solution without using an If Statement. My assignment explicitly says I cannot use an If Statement, so I am currently at a standstill.
I'm not going to answer your question exactly, but point you to the concept...
Most languages offer a modulus operator. (%) This is the equivalent of doing a division, but instead of returning the quotient, it returns you the remainder.
int n = 26%12; // 26 divided by 12 = 2 remainder 4. n = 4
One use for the modulus operator is to efficiently do a wrap around. For example, if you wanted to print out the numbers 1 to 7 repeatedly...
int n = 0;
for(int i = 0; i < 10; ++i) {
Console.log(n+1);
n = (n+1)%7;
}
This would output
1
2
3
4
5
6
7
1
2
3
I apologize if this is a simple question but I'm having trouble grasping the concept of modulus division when the first number is smaller than the second number. For example when 1 % 4 my book says the remainder is 1. I don't understand how 1 is the remainder of 1 % 4. 1 / 4 is 0.25. Am I thinking about modulus division incorrectly?
First, in Java, % is the remainder (not modulo) operator, which has slightly different semantics.
That said, you need to think in terms of integer-only division, as if there were no fractional values. Think of it as storing items that cannot be divided: you can store zero items of size 4 in a storage of overall capacity one. Your remaining capacity after storing the maximum number of items is one. Similarly, 13%5 is 3, as you can fit 2 complete items of size 5 in a storage of size 13, and the remaining capacity is 13 - 2*5 = 3.
If you divide 1 by 4, you get 0 with a remainder of 1. That's all the modulus is, the remainder after division.
I am going to add a more practical example to what "Jean-Bernard Pellerin" already said.
It is correct that if you divide 1 by 4 you get 0 but, Why when you do 1 % 4 you have 1 as result?
Basically it is because this:
n = a / b (integer), and
m = a % b = a - ( b * n )
So,
a b n = a/b b * n m = a%b
1 4 0 0 1
2 4 0 0 2
3 4 0 0 3
4 4 1 0 0
5 4 1 4 1
Conclusion: While a < b, the result of a % b will be "a"
Another way to think of it as a representation of your number in multiples of another number. I.e, a = n*b + r, where b>r>=0. In this sense your case gives 1 = 0*4 + 1. (edit: talking about positive numbers only)
I think you are confused between %(Remainder) and /(Division) operators.
When you say %, you need to keep dividing the dividend until you get the remainder 0 or possible end. And what you get in the end is called Remainder.
When you say /, you divide the dividend until the divisor becomes 1. And the end product you get is called Quotient
Another nice method to clear things up,
In modulus, if the first number is > the second number, subtract the second number from the first until the first number is less than the second.
17 % 5 = ?
17 - 5 = 12
12 % 5 = ?
12 - 5 = 7
7 % 5 = ?
7 - 5 = 2
2 % 5 = 2
Therefore 17 % 5, 12 % 5, 7 % 5 all give the answer of 2.
This is because 2 / 5 = 0 (when working with integers) with 2 as a remainder.
I have some problem with numerator, denumerator and modulo. 7 / 3 = 2.3333333333 gives me a modulo of 1!? Must be some wrong? I study a non-objective ground level course, so my code is simple and I have simplified the code below. (Some lines are in swedish)
Calling the method:
// Anropar metod och presenterar beräkning av ett bråktal utifrån täljare och nämnare
int numerator = 7;
int denumerator = 3;
System.out.println("Bråkberäkning med täljare " + numerator + " och nämnare " + denumerator + " ger " + fraction(numerator,denumerator));
And the method:
// Metod för beräkning av bråktal utifrån täljare och nämnare
public static String fraction(int numerator, int denumerator) {
// Beräkning
int resultat1 = numerator / denumerator;
int resultat2 = numerator % denumerator;
return Integer.toString(resultat1) + " rest " + Integer.toString(resultat2);
}
3 goes into 7 twice with 1 left over. The answer is supposed to be 1. That's what modulo means.
7 modulo 3 gives 1. Since 7 = 2*3 + 1.
7 % 3 = 1
Just as expected. If you want the .3333 you could take the modulo and devide it by your denominator to get 1 / 3 = 0.3333
Or do (7.0 / 3.0) % 1 = 0.3333
Ehm 7 % 3 = 1
What would you expect?
Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) can be thought of as the remainder, on division of a by n. For instance, the expression "5 mod 4" would evaluate to 1 because 5 divided by 4 leaves a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3. (Notice that doing the division with a calculator won't show you the result referred to here by this operation, the quotient will be expressed as a decimal.) When either a or n is negative, this naive definition breaks down and programming languages differ in how these values are defined. Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands.
More info : http://en.wikipedia.org/wiki/Modulo_operation
you didn't do a question!
And if your question is just:
"...gives me a modulo of 1!? Must be some wrong?"
No, it isn't, 7/3 = 2, and has a modulo of 1. Since (3 * 2) + 1 = 7.
You are using integer operands so you get an integer result. That's how the language works.
A modulo operator will give you the reminder of a division. Therefore, it is normal that you get the number 1 as a result.
Also, note that you are using integers... 7/3 != 2.3333333333.
One last thing, be careful with that code. A division by zero would make your program crash. ;)
% for ints does not give the decimal fraction but the remainder from the division. Here it is from 6 which is the highest multiplum of 2 lower than your number 7. 7-6 is 1.