How could the following function be written using iteration instead of recursion?
function mystery(b)
{
if b == 0 then
return 0
if (b / 2 == 0)
return mystery (b-1) + 3
else
return mystery (b-1) + 2
}
I assume that when you are doing b / 2 == 0 you are checking whether the number b is even or odd otherwise that is true only for case where b= 0,1.
Recursive function
def mystery(b):
if b == 0:
return 0
if b % 2 == 0:#check if b is even
return mystery(b-1)+3
else: return mystery(b-1)+ 2
Iterative function
def mystery_iter(b):
result= 0
while b > 0:
if b % 2 == 0:#check if b is even
result += 3
b= b-1
else:
result += 2
b= b-1
return result
At least two people suggest you reformulate the recursion as a loop. I instead suggest you first try to understand the mathematics of what the function is doing before considering unwinding the implicit recursive loop into an explicit iterative loop. Doing so in this case, you get a simpler answer:
def mystery(b):
if b == 0:
return 0
if b % 2 == 0:
return b // 2 * 5
return b // 2 * 5 + 2
This could be further reduced code-wise, possibly to a one-liner, if one desires. (Like #AkhileshPandey, I'm assuming that the division in (b / 2 == 0) was supposed to be a modulus operation (b % 2 == 0)) The above example is Python 3 as it wasn't clear what language the OP used, nor that the given code would run correctly in said language due to inconsistent use of then.
Related
I wrote this program in python to find the factorial of given input n:
def factorial(n):
count = n
if n == 1:
return n
else:
while count != 0:
return n * n-1
n -= 1
count -= 1
When I run it multiple times, it comes up with multiple answers for the same input. For example, I will run it at n = 5 and it returns 120 sometimes and 24 other times. This holds true for all of the numbers that I have tried. Why is this so?
Thanks!
You have error in logic. First of all, you are multiplying n by itself, and deduce 1 from it (missing brackets). Second, you should call factorial function recursively, in which case you don't need extra variable (count) and don't need while loop:
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
The logic is wrong overall. When you pass 5 every single time the result will be 24 the reason is return n * n-1 part. In the loop it should be n*=n-1 instead of return n * n-1 Also your loop must be while n>1 and remove count at all. Good luck at school :)
def fact(n):
if n<=1:
return 1
else:
return n * fact(n-1)
I wanted to calculate the number of solutions of the equation, but I am unable to get any lead. The equation is:
All I could get is by doing something like,
But I don't know how to proceed on this.
I'd try solving this by using dynamic programming.
Here's some pseudocode to get you started:
Procedure num_solutions(n, k, m):
# Initialize memoization cache:
if this function has been called for the first time:
initialize memo_cache with (n+1)*(k+1)*(m+1) elements, all set to -1
# Return cached solution if available
if memo_cache[n][k][m] is not -1:
return memo_cache[n][k][m]
# Edge case:
if m is equal to 1:
# Solution only exists if 1 <= m <= k
if n >= 1 and n <= k, set memo_cache[n][k][m] to 1 and return 1
otherwise set memo_cache[n][k][m] to 0 and return 0
# Degenerate case: No solution possible if n<m or n>k*m
if n < m or n > k * m:
set memo_cache[n][k][m] to 0 and return 0
# Call recursively for a solution with m-1 elements
set sum to 0
for all i in range 1..k:
sum = sum + num_solutions(n - i, k, m - 1)
set memo_cache[n][k][m] to sum and return sum
I was looking at the following code:
function _fibonacci(n) {
if (n < 2){
return 1;
}else{
return _fibonacci(n-2) + _fibonacci(n-1);
}
}
console.log(_fibonacci(5))
I understand HOW this works, but I do not understand WHY this works. Can someone explain to me why this works?
It's quite simple, the fibonacci answer for both location 0 and 1 are both 1 (the sequence looks like 1 1 2 3 5 8 etc...) so when it enters the function with n being 0 or 1 (which can happen for both the n-2 recursive call and the n-1 recursive call), the result is 1. For all other values it just keeps adding the numbers.
(Note that the values for the first 2 in the sequence can be 0 1 or 1 1, depending on your definition of the sequence. For this one it's apparently assumed the first 2 are both 1.)
The regular recursive approach for pow(x,n) is as follows:
pow (x,n):
= 1 ...n=0
= 0 ...x=0
= x ...n=1
= x * pow (x, n-1) ...n>0
With this approach 2^(37) will require 37 multiplications. How do I modify this to reduces the number of multiplications to less than 10? I think this could be done only if the function is not excessive.
With this approach you can compute 2^(37) with only 7 multiplications.
pow(x,n):
= 1 ... n=0
= 0 ... x=0
= x ... n=1
= pow(x,n/2) * pow (x,n/2) ... n = even
= x * pow(x,n/2) * pow(x,n.2) ... n = odd
Now lets calculate 2^(37) with this approach -
2^(37) =
= 2 * 2^(18) * 2^(18)
= 2^(9) * 2^(9)
= 2 * 2^(4) * 2^(4)
= 2^(2) * 2^(2)
= 2 * 2
This function is not excessive and hence it reuses the values once calculated. Thus only 7 multiplications are required to calculate 2^(37).
You can calculate the power of a number in logN time instead of linear time.
int cnt = 0;
// calculate a^b
int pow(int a, int b){
if(b==0) return 1;
if(b%2==0){
int v = pow(a, b/2);
cnt += 1;
return v*v;
}else{
int v = pow(a, b/2);
cnt += 2;
return v*v*a;
}
}
Number of multiplications will be 9 for the above code as verified by this program.
Doing it slightly differently than invin did, I come up with 8 multiplications. Here's a Ruby implementation. Be aware that Ruby methods return the result of the last expression evaluated. With that understanding, it reads pretty much like pseudo-code except you can actually run it:
$count = 0
def pow(a, b)
if b > 0
$count += 1 # note only one multiplication in both of the following cases
if b.even?
x = pow(a, b/2)
x * x
else
a * pow(a, b-1)
end
else # no multiplication for the base case
1
end
end
p pow(2, 37) # 137438953472
p $count # 8
Note that the sequence of powers with which the method gets invoked is
37 -> 36 -> 18 -> 9 -> 8 -> 4 -> 2 -> 1 -> 0
and that each arrow represents one multiplication. Calculating the zeroth power always yields 1, with no multiplication, and there are 8 arrows.
Since xn = (xn/2)2 = (x2)n/2 for even values of n, we can derive this subtly different implementation:
$count = 0
def pow(a, b)
if b > 1
if b.even?
$count += 1
pow(a * a, b/2)
else
$count += 2
a * pow(a * a, b/2)
end
elsif b > 0
a
else
1
end
end
p pow(2, 37) # 137438953472
p $count # 7
This version includes all of the base cases in the original question, it's easy to run and confirm that it calculates 2^37 in 7 multiplications, and doesn't require any allocation of local variables. For production use you would, of course, comment out or remove the references to $count.
Given an X, what math is needed to find its Y, using this table?
x
y
0
1
1
0
2
6
3
5
4
4
5
3
6
2
This is a language agnostic problem. I can't just store the array, and do the lookup. The input will always be the finite set of 0 to 6. It won't be scaling later.
This:
y = (8 - x) % 7
This is how I arrived at that:
x 8-x (8-x)%7
----------------
0 8 1
1 7 0
2 6 6
3 5 5
4 4 4
5 3 3
6 2 2
int f(int x)
{
return x["I#Velcro"] & 7;
}
0.048611x^6 - 0.9625x^5 + 7.340278x^4 - 26.6875x^3 + (45 + 1/9)x^2 - 25.85x + 1
Sometimes the simple ways are best. ;)
It looks like:
y = (x * 6 + 1) % 7
I don't really like the % operator since it does division so:
y = (641921 >> (x*3)) & 7;
But then you said something about not using lookup tables so maybe this doesn't work for you :-)
Update:
Since you want to actually use this in real code and cryptic numbers are not nice, I can offer this more maintainable variant:
y = (0x2345601 >> (x*4)) & 15;
Though it seems a bunch of correct answers have already appeared, I figured I'd post this just to show another way to have worked it out (they're all basically variations on the same thing):
Well, the underlying pattern is pretty simple:
x y
0 6
1 5
2 4
3 3
4 2
5 1
6 0
y = 6 - x
Your data just happens to have the y values shifted "down" by two indices (or to have the x values shifted "up").
So you need a function to shift the x value. This should do it:
x = (x + 5) % 7;
Resulting equation:
y = 6 - ((x + 5) % 7);
Combining the ideas in Dave and Paul's answer gives the rather elegant:
y = (8 - x) % 7`
(though I see I was beaten to the punch with this)
unsigned short convertNumber(unsigned short input) {
if (input <= 1) { return !input; } //convert 0 => 1, 1 => 0
return (8-input); //convert 2 => 6 ... 6 => 2
}
Homework?
How about:
y = (x <= 1 ? 1 : 8) - x
and no, i dont/cant just store the array, and do the lookup.
Why not?
yes, the input will always be the finite set of 0 to 6. it wont be scaling later.
Just use a bunch of conditionals then.
if (input == 0) return 1;
else if (input == 1) return 0;
else if (input == 2) return 6;
...
Or find a formula if it's easy to see one, and it is here:
if (input == 0) return 1;
else if (input == 1) return 0;
else return 8 - input;
Here's a way to avoid both modulo and conditionals, going from this:
y = (8 - x) % 7
We know that x % y = x - floor(x/y)*y
So we can use y = 8 - x - floor((8 - x) / 7) * 7
What about some bit-fu ?
You can get the result using only minus, logical operators and shifts.
b = (x >> 2) | ((x >> 1) & 1)
y = ((b << 3)|(b ^ 1)) - x