I am trying to understand how to repeat loops using the mod operator.
If you have two strings, "abc" and "defgh", how can % be used to loop through abc, repeating it until the end of defgh is reached? Namely, what is the mod relationship of the length of abc and defgh?
I don't really understand this concept.
Simple.
std::string abc("abc");
std::string defgh("defgh");
for (size_t i = 0; i < defgh.length(); ++i)
{
printf("%c", abc[i % abc.length()]);
}
Think about what the Modulus operator is doing, it discretely divides the left hand side by the right hand side, and spits back the integer remainder.
Example:
0 % 3 == 0
1 % 3 == 1
2 % 3 == 2
3 % 3 == 0
4 % 3 == 1
In our case, the left hand side represents the i'th position in "defgh", the right hand represents the length of "abc", and the result the looping index inside "abc".
The typical usage of mod is for generating values inside a fixed range. In this case, you want values that are between 0 and strlen("abc")-1 so that you don't access a position outside "abc".
The general concept you need to keep in mind is that x % N will always return a value between 0 and N-1. In this particular case, we also take advantage of the fact that if you increase x by 1 x % N also increases by 1. See it?
Another important property of modulus that we use here is the fact that it "rolls over". As you increase x by 1, x % N increases by 1. When it hits N-1, the next value will be 0, and so on.
Look at #Daniel's code. It's C++ but the concept is language-agnostic
Related
Atually i have i understand the code but doesn't understand the logic of the code.I know what is going on but i doesn't know what is happening.The code is of even or odd.The code is.
#include<stdio.h>
int main() {
int i;
for(i=1; i<26; i++) {
if(i%2==1)
printf("%d\n",i);
}
return 0;
}
output:
1
3
5
7
9
11
13
15
17
19
21
23
25.
1st repitition:-
(i=1;i<26;i++)
if(i%2==1)
1%2==1
but the result of 1%2 is 0.
I am still getting 1 on my screen. I don't know how I get this '1' , even 1 is
not equal to 0.
2nd repitition:-
(i=1;i<26;i++)
if(i%2==1)
now, at 2nd repition i is 2. AND (2%2) is equal to 0 and 0 is not equal to 1 as follows (0==1) and i am getting 3 on my output screen as i mention above on my screen.
Either I didn't use if condition. how i get this 3 and so on.
The modulo operator gives your the remainder after integer division. Integer division is different to standard (floating point) division.
1/2 = 0.5 (floating point division)
1\2 = 0 (integer division)
Integer Division
Integer division tells you the total number of times the second number 'fits' inside the first number. It's more obvious with a bigger example:
10/3 = 3.333 etc.
10\3 = 3
You cannot fit another entire 3 into 10.
Modulo (the complement of Integer Division)
Modulo tells you how much space you have left (the remainder). After you put three 3s into 10, you have 1 space left.
10%3 = 1 (i.e. 10-3*3)
If you used 11 instead of 10, you would have 2 spaces left. If you used 12, you could fit another whole 3 in, leaving no space left.
10\3=3 (with 1 space remaining)
11\3=3 (with 2 spaces remaining)
12\3=4
13\3=4 (with 1 space remaining)
Modulo gives you the amount of space remaining:
10%3=1
11%3=2
12%3=0
13%3=1
etc.
Modulo by 2 (to assess even/odd)
In your example, you're doing modulo 2. You cannot fit any whole 2s into 1.
1\2=0 (quotient)
1%2=1 (remainder)
So... In your loop:
i=1 > 1%2=1 > 1==1 (true) > print 1
i=2 > 2%2=0 > 0==1 (false) > do nothing
i=3 > 3%2=1 > 1==1 (true) > print 3
i=4 > 4%2=0 > 0==1 (true) > do nothing
Modulus operator % in this case returns 0 if the number is even and 1 if the number is odd. So, your code:
for(i=1; i<26; i++) {
if(i%2==1)
printf("%d\n",i);
}
checks if the number is odd, and if it is, prints it out. That's the logic behind the modulus operator.
I would suggest in later use to modify this code into:
for(i=1; i<26; i++) {
if(i%2!=0)
printf("%d\n",i);
}
to avoid mistakes with negative numbers.
Read this!
I don't know which part of the comments you didn't understand, but the gist is:
1%2 is NOT 0, but 1.
Either you accept that, and then the program's behavior should be clear, or you don't accept it, and then you did not understand what the % operator does. Go and read up on it.
I'm having trouble understanding the format a while(loop) uses.
How would I go about making one for example one that computes the sum of all multiples of 5 and 9 between a set range of numbers?
while STATEMENT:
CODE BLOCK
The basic format of any while loop is such that "CODE BLOCK" is executed as long as "STATEMENT" holds true.
For example:
x = 6
while (x > 5) and (x < 20):
x = x + 1
As long as x is greater than 5 and less than 20 x will be incremented by one. The loop will terminate when x is equal to twenty. If I had initialized x to 0, the loop would never enter the block and x will remain zero.
Hopefully that helps
I came across this problem while solving challenges on Hackerrank.
/*
Problem Statement
There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.
Input Format
The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.
Constraints
1≤N<100
N % 2=1 (N is an odd number)
0≤A[i]≤100,∀i∈[1,N]
Output Format
Output S, the number that occurs only once.
*/
The normal solution which I would write in this case turned out to be extremely complicated, with lots of nested if loops. On searching a bit, I found this solution which solves the problem by simply XOR-ing all the elements in the integer array with each other, and the result is the lonely integer.
Here's the related method (main() method which accepts input and parses it into integer array not shown as it's not relevant here) :
static int lonelyinteger(int[] a) {
int n = a.length;
int result = 0;
for( int i = 0; i < n; i++) {
result = result ^ a[i];
}
return result;
}
I am not sure how this XOR operation is able to return the "lonely integer" in the array. I'm aware of the two properties of XOR, as:
1. a^a=0
2. a^0=a
But other than this, I couldn't quite figure out how XOR worked here.
There is another question on SO with the same content, but that asks a different question, so I had to ask this (again).
I'd highly appreciate if anyone could provide a detailed explanation for this XOR operation.
Since a^a is equal to 0 for any a, all of the matching pairs of integers will cancel each other out, leaving 0. That is then XOR'ed with the final number. Since 0^a is equal to a for any a, the result will be that final number.
Simple demo:
$ ruby -e 'puts [1,1,2,2,3,3,4,5,5,6,6].reduce :^'
4
You can see why this works if you go through the individual pairs:
1 ^ 1 = 0
0 ^ 2 = 2
2 ^ 2 = 0
0 ^ 3 = 3
3 ^ 3 = 0
0 ^ 4 = 4
4 ^ 5 = 1
1 ^ 5 = 4
4 ^ 6 = 2
2 ^ 6 = 4
The result toggles between 0 and the latest number until you get to the loner; after that it toggles between that number and... whatever you get when you XOR it with the latest new number. The actual value there doesn't matter because it will be zapped when you XOR in the second copy of that number, and you're back to the copy of the singleton.
I sorted the numbers to make it easy to spot the singleton, but since XOR undoes itself, the order doesn't matter at all:
$ ruby -e 'puts [6,3,4,1,1,2,2,6,3,5,5].reduce :^'
4
6 ^ 3 is ... some number, and then that number ^ 4 is some other number, and then you XOR that with 1, and none of that matters because then you undo the 1, and then you throw in another intermediate result with the 2 and undo it right away, and then you undo the 6 and the 3, so you're back to just the 4. Which you XOR with 5 to get another ephemeral number that is then washed away by the final 5, leaving, once again, 4.
I found the following code for computing nCr, but don't understand the logic behind it. Why does this code work?
long long combi(int n,int k)
{
long long ans=1;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
that's a clever code!
In general it aims to calculate the following formula:
ans = n! / (k!)(n-k)!
It is equal to:
ans = n(n-1)(n-2) ... (n-k)...1 / k(k-1)...1 * (n-k)(n-k-1) ... 1
And after obvious cancellation:
ans = n(n-1)(n-2)..(n-k+1) / k!
Now notice that nominator and denominator have the same number of elements (k element)
So the calculation of ans will be like the following:
ans = 1 // initially
ans *= n/1
ans *= (n-1)/2
ans *= (n-2)/3
.
.
.
ans *= (n-k+1)/k
take a look again at the code and you notice that:
ans is being multiplied by n at each iteration
n is reduced by 1 at each iteration (n--)
ans is divided by j at each iteration
This is exactly what is done by the posted code, Now let's see the meanings of different conditions in the loop, with nominator starting from n and denominator from 1 to k, so variable j is assigned to denominator right?
1) if(n%j==0)
at each step if n/j is (computable) So we calculate it first here than multiply to the whole ans, this practice keeps the result at its smallest possible value.
2) else if(ans%j==0)
at each step if we couldn't calculate n/j but actually can calculate ans/j so that's not bad to say :
ans /= j; //first we divide
ans *= n; //then we multiply
This is always keeping our overall output as small as possible, right?
3) last condition
at each step, if we couldn't compute neither n/j nor ans/j in this case we are not lucky enough to divide first then multiply (hence keeping the result small). But well we need to carry on even-though we are left with only one choice which is
ans *= n; // multiply first
ans /= j; // then divide
ET VOILA!
Example
consider the case 3C7
we know that the answer is 7!/ 3!*4!
hence : ans = 7*6*5 / 1*2*3
let's see what happen at each iteration:
//1
ans = 1
//2
n = 7
j = 1
ans = ans * n/j
first compute 7/1 = 7
then multiply to ans
ans = 1*7
ans = 7
//3
n = 6
j = 2
ans = ans* n/j
evaluate n/j = 6/2 (can be divided)
n/j = 3
ans = ans *(n/j)
= 7 * 3
= 21
// 4
n = 5
j = 3
ans = ans * n/j
evaluate n/j = 5/3 oppsss!! (first if)
evaluate ans/j = 21/3 = 7 YES (second if)
ans = (ans/j)*n
= 7*5
= 35
// end iterations
Note that in last iteration if we calculate straight forward we would say:
ans = ans*n/j
= 21 * 5 / 3
= 105 / 3
= 34
yes it does find right result but meanwhile the value flies up to 105 before getting back to 35. Now imagine calculating real large numbers?!
Conclusion
This code is computing carefully the binomial coefficients trying to keep the output as small as possible at each step of calculation, it does that by checking if it is possible to divide (int) then execute, hence it is capable of calculating some very big kCn that the straightforward coding cannot handle (OverFlow may occur)
To answer the question in part, consider the fact that the entries of n choose k constitute Pascal's triangle. As Pascal's triangle is symmetric, it is sufficient to move the argument k into the left half, which is done with the
k=k>n-k?n-k:k;
statement; see the definition of C's conditional operator.
Furthermore, the result ans is initialized in the beginning to contain 1, which is the first entry of every row in Pascal's triangle, which means that initially, ans is in fact n choose j.
The fact is that nCr for 1<=k<=n/2 is same as in n/2+1<=k<=n.so first change in k so that it values lies value in the left half.One more thing nCk means (n*(n-1).....(n-k))/(k*(k-1)*....*2*1) so the above code apply it iteratively.
yes.
[N choose K] reduces its factorials a lot because the dividend and divisor share many factors that cancel each other out to x/x=1 (for x>0)
the trick is to not calculate the large factorials, because these large factors require too much address space (too many bits)
the first trick is to reduce the fraction, before dividing.
the second trick is to do modulo within a conditional to chose one of 3 operations for the current iteration. this can be done differently, and integer modulo is chosen to be a fast operator, skipping some slower integer division approaches.
you iteratively traverse pascals triangle.
with each path that you take, you multiply something.
There are 3 possible branching paths for every iterative step:
each of the 3 steps multiplies the accumulator "ans" with a different value, representing the factor between 2 "positions" on pascals triangle.
you always end up doing N multiplications, where N is the number of iterations, and end up at the binomial coefficient's value.
N is the column # of pascals triangle that you want to know, and you accumulate an N, multiplied by something, while reducing the number of column s (and lines) of pascals triangle by N=N-1 for each iteration.
j=1;
ans=0;
//within each iteration;
ans=ans*n;
n=n-1;
ans=ans/j;
j=n+1;
the integer division is slow and can be skipped (or made faster by making the divisor smaller) at least once, and often many more times (because there are a lot of shared prime factors in pascals triangle), this is being done by the modulo conditionals.
pascals triangle is extremely symmetric (on summing up its domains), therefore this works.
the difference between (partial) sums of columns of pascals triangle shows the symmetry that is important for the multiplications and divisions here.
just watch some youtube videos on the symmetries and identities of pascals triangle.
Here is a C language function, which I am having a little trouble understanding. I need to show what values of r come out when I input values of 6 or 10 or 13 into the function:
int factor(int val){
int r=val-1;
while(val%r){
r--;
}
return r;
}
I'm not sure if I misunderstood the question but wouldn't the remainder always be true? Since 0 = false and the while statement never reaches 0 because r is always smaller than val and not equal to it, and each time r decreases the remainder just gets bigger?
Edit: Just realized i forgot to account that 6%3 = 0! thanks for the help people who helped!
Test for yourself: 4 % 2.
The result should be 0 as the % operator returns the remainder of a division.
while(x % y) {} translates in this context to something like: as long as x is not dividable by y, do something, whereby 'do something' is decrease y in your case.
Essentially, the function returns the largest factor of the number input to the method.
It translates to "while there is a remainder from division (r is NOT a factor of val), decrease r by 1 and check again. Once the clean factor is found (val % r is 0), return the factor (r).
Here's a JavaScript port with sample output:
http://jsfiddle.net/43HxX/2/
I rewrote it in JS and you can uncomment the alert(...) line to see the output for 6, 10, and 13