Learning about recursion and having trouble with the code posted below, in line 6,
int result=fact(n-1)*n;
When I delete "fact" the program acts like I think it would, printing out:
Factor of 3 6
Factor of 4 12
Factor of 5 20
but with the "fact" in it gives the output below? What is this line doing, and what is "fact" ? thanks everyone.
Factor of 3 6
Factor of 4 24
Factor of 5 120
Factorial is often used as an example of something which can be performed using recursion.
For example, factorial of 5 is calculated as follows:
5! = 5 * 4 * 3 * 2 * 1
Also, there is another way of thinking about it:
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1
The way the second series of equalities are written, it can be seen that a factorial can be calculated in a recursive fashion. For example:
5! = 5 * 4! --> 5! = 5 * (4 * 3!) --> 5! = 5 * (4 * (3 * 2!)) --> and so on.
The fact function in the question is performing the factorial function as written in the second series of equalities:
fact(n) = n * fact(n-1);
So, when the fact method is being called, way it is being called can be thought as something like the following:
fact(5) --> fact(5 * fact(4)) --> fact(5 * fact(4 * fact(3))) --> and so on.
Also, it should be noted as Kip points out in the comments, calculating the factorial of a number can be much easily and quickly calculated by iterating over the range of numbers from n to 1 and multiplying it together to calculate the result.
Apparently this is the classic example of recursion using the factorial calculation.
What you're calling fact(N) is usually denoted by N! (by mathematicians, anyway)
n! = n x (n-1) x (n-2) ...
so
5! = 5 x 4 x 2 x 1 = 120
4! = 4 x 3 x 2 x 1 = 24
Incidentally, this may be a little counterintuitive, but 0! is defined as 1
fact(5) = fact(4) * 5
fact(4) = fact(3) * 4
fact(3) = fact(2) * 3
fact(2) = fact(1) * 2
fact(1) = 1
fact(5) = fact(4) * 5 = fact(3) * 4 * 5 = .. = 1 * 2 * 3 * 4 * 5 = 120
Function recuresively calls itself so it unwraps calculation to 1 * 2 * 3 * 4 * 5.
When you remove the call to fact again you are just doing:
println(n * (n-1))
You may want to try doing a factorial with just a loop and see how different the code is.
Recursion can be useful, but, you will be limited in how large of (n) you can call, as you will eventually overflow the stack, since the calculations won't happen until you reach the condition that marks the end of the recursion.
To better understand recursion you can look at this link:
http://en.wikipedia.org/wiki/Recursion_(computer_science)
Related
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
1 - 1
2 - 2,3
3 - 4,5,6
4 - 7,8,9,10
Given any number from 4 to 6 ,I need the output as 3.
Given any number from 7 to 10 ,I need the output as 4.
I need the fastest solution for the above problem to solve an algorithm.
What I could think of is a brute force algorithm :
Given 7:
n-square + n = 7*2 = 14
1 + 1 = 2 < 14
4 + 2 = 6 < 14
9 + 3 = 12 < 14
16+ 4 = 20 >=14 --> So 4
Is there any better approach to arrive at the solution ? OR My approach to the algorithm itself is flawed ?
Brief explanation of the algo :
A,B,C
After every iteration every element becomes increased by one.
A,A,B,B,C,C
Given 3, C will be returned.
Given 4 or 5, A will be returned.
Given 6 or 7, B will be returned.
Given 8 or 9, C will be returned.
Given 10 or 11 or 12, A will be returned.
Given 13 or 14 or 15, B will be returned.
How the solution to the mathematical problem will help solve the algo :
Total number of elements = 3
Given number = 13 (Output to be B)
Divide and Ceiling = Ceil (13/3) = 5 [So 13 falls under when every element has become * 3] (From Mathematical problem : If given number is 5, 3 is to be used)
Starting index of when every element has become * 3 [IS_EQUAL_TO = ] 3 * 3(summation of previous iteration => 1 + 2) + 1 = 10
To Find the index = Ceil(13-10+1/3 (this 3,comes from the mathematical problem) ) = Ceil (4/3) = 2nd index = B
Given number of rows N, the size of the triangle is N(N+1)/2. You are essentially trying to find the least integer N such that N(N+1)/2 >= M, with M given. If you have a function to compute square roots, you can solve this equation in constant time.
N(N+1)/2 >= M, multiply both sides with 2,
N²+N >= 2M, complete the square, take the square root, blablabla
N >= sqrt(2M+1/4)-1/2
Therefore the answer is N = ceil(sqrt(2*M + .25) - .5)
This question already has answers here:
Understanding how recursive functions work
(18 answers)
Closed 7 years ago.
Please explain the working of the recursion statement in the following code.
int factR(int n) {
int result;
if(n==1) return 1;
result = factR(n-1) * n;
return result;
}
My understanding is that:
In the above statement the factR(n-1) method calls itself until the end. Suppose we want to get the factorial of 6, which will be sent to this method as an argument. It will be received as the parameter n, and the value of n will then be checked; if it is 1 then 1 will be returned. But if it is not 1, as in our case where it is 6, then the recursion statement will run.
Now the problem I face is that the first time n-1 becomes 5 and is multiplied by n, which holds the value 6, then it becomes 30. Now where will that 30 GO?
Then the method will call itself and this time n-1 becomes 4 and it then multiplies with n which IF holds the value "6" then 4*6=24 which I think is wrong. Because if we go through this way then in the next call
the process will be something like, n-1 will become 3*n which IF holds the same value i.e. 6 then it will become 3*6= 18. Then next call occurs and n-1 becomes 2 if we multiply and suppose that n holds the value 6 then 2*6= 12, and at last call n-1= 1 * n = 6. My point is that it is clear that n-1 will decrease the value n-1 i.e. 6-1=5 then 5-1=4 then 4-1=3 then 3-1=2 and 2-1=1. BUT the question is what will be the value of n which will be multiplied each time when the method calls itself?
If you say that when the first multiplication happens i.e. "n-1" become 5 then multiplied by 6 = 30 and that 30 is stored at "n" then in the next call 5-1=4*30=120, then 4-1=3*120=360 , then 3-1=2*360=720, and at last 1*720=720 then how does Java determine to put the resulting value back into the variable n?
If I place another statement to check what is the value of variable result each time the method call itself in this way, like this:
int factR(int n) {
int result;
if(n==1) return 1;
result = factR(n-1)*n ;
System.out.println(result);
return result;
}
Then I get this output:
2
6
24
120
720
Factorial of 6 is 720
I don't understand how it produces 2 in its first call. Where does the value 2 and then 6, 24, 120 and 720 come from? I think I am severely stuck in the working of the code.
The function expands until the termination statement is reached (n == 1). So suppose n = 6, then we have factR(n-1) * n = factR(5) * 6, but what is factR(5)? Well it is just factR(4) * 5, and so we see that factR(5) * 6 = (factR(4) * 5) * 6. Now note that factR(1) = 1, and we get
factR(6) = factR(5) * 6
= (factR(4) * 5) * 6
= ((factR(3) * 4) * 5) * 6
= (((factR(2) * 3) * 4) * 5) * 6
= ((((factR(1) * 2) * 3) * 4) * 5) * 6
= ((((1 * 2) * 3) * 4) * 5) * 6
= (((2 * 3) * 4) * 5) * 6
= ((6 * 4) * 5) * 6
= (24 * 5) * 6
= 120 * 6
= 720
What you might be missing out here is that n is a variable local to your function. This means every call to your function (may it through recursion or not) gets a new variable n, which contains the parameter of that function. Because it is a value type, it is copied and not a reference to the original value. Therefore any changes to it in one call do not affect the variables in other (recursive) calls.
As a result your function first gets a copy of 6 and gives that reduced by 1 as a copy to the next call of your function. That call gets a "copy" of 6-1=5 and reduces it again - and so on. When it reaches 1 it also returns 1. Then it works its way up again through the call stack and multiplies the result of the last call with the local variable in this call. So 1 gets multiplied with 2 and gets returned. That result gets multiplied with 3 and so on. Finally you end up with the factorial.
In java, we have something called a stack.
Each time a method gets called by another method, it gets added to the stack.
________
|factR(1)| = <prints nothing>
________
|factR(2)| = 2
________
|factR(3)| = 6
________
|factR(4)| = 24
________
|factR(5)| = 120
________
|factR(6)| = 720
This basically means that for the factR(6) method to complete, factR(5) must complete, for factR(5) to complete, factR(4) must complete and so on.
In factR(6) you make a call to factR(5) and then wait for it to complete, because the result depends on it.
But, in factR(5), you too make a recursive call and you have to wait.
And so on, until we hit the limit factR(1), which will just return 1.
With factR(1) complete, factR(2) can then print out the result and return the result to its parent method, and so on, until factR(6) prints out and returns its results
The method should really be structured like this to find the factorial of n:
int factorial(int n)
{
if (n == 1)
return 1;
return n * factorial(n - 1);
}
It isn't a very good idea, in my opinion to instantiate new variables inside of a recursive function because they'll simply be reset with each call because of scope.
I would like to check if the result is measurable; that is, whether it has a finite number if decimal places. What do i mean?
double x = 5.0 / 9.0; // x = 0.(5)
x is not measurable.
I want to round x to the second digit ( x = 0.56 ), but in such case:
double x = 1.0 / 8.0; // x = 0.125
I don't want to round anything.
So here is my question. How do i decide if the result can be measured or not?
You cannot. That is the reason, why 1.0 / 3 / 100 * 3 * 100 gives you 0.9999...9. You only have so many bits to represent the numbers. You cannot distinguish between the period
1.0 / 3 and a number that actually has 0.3333.....3 as value
The only fractions which will be exactly represented in a binary will be ones where the denominator is a power of two. If your input is two integers for the numerator and denominator then find the prime factorisation of both and remove the common factors. Then check the only remaining factors on the denominator are power of 2. Say if we want to find 56 / 70 this is 2^3 * 7 / ( 2 * 5 * 7) removing common factors gives 2^2 / 5 so that will not work. But 63 / 72 = (7*3^2) / (2^3 * 3^2) = 7 / 2^3 so will be a terminating binary number
If your working in decimal then powers of 2 and 5 on the denominator will be allowed.
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.