Recursive call for x power y power z - recursion

Recently i attended an interview where i was asked to write a recursive java code for (x^y)^z.
function power(x,y){
if(y==0){
return 1;
}else{
x*=power(x,y-1);
}
}
I could manage doing it for x^y but was not getting a solution for including the z also in the recursive call.
On asking for a hint, they told me instead of having 2 parameters in call u can have a array with 2 values. But even then i dint get the solution. can u suggest a solution both ways.

This is the solution I would use in python, but you could easily have done it in javascipt or any other language too:
def power(x, y):
if y == 0:
return 1
if y == 1:
return x
return x * power(x, y - 1)
def power2(x, y, z):
return power(power(x, y), z)
You can then use power2 to return your result. In another language you could probably overload the same function but I do not think this is possible in Python for this scenario.
For your javascript code, all you really needed to add to your solution was a second function along the lines of:
function power2(x,y,z)
{
return power(power(x, y), z);
}
As you can see, the solution itself is also recursive despite defining a new function (or overloading your previous one).

Michael's solution in Java Language
public void testPower()
{
int val = power(2, 3, 2);
System.out.println(val);
}
private int power(int x, int y, int z)
{
return power(power(x, y), z);
}
private int power(int x, int y)
{
if (y == 0)
{
return 1;
}
if (y == 1)
{
return x;
}
return x * power(x, y - 1);
}
output is 64

Related

Calculating a value to return using recursion

In this recursive method, I am trying to calculate a number using the initial call mystery5(-23, -48). After going through my first series of if statements, I get to the numbers 23 and 48. Once I get to the else branch of the decision statements, what precedence does the method call have in the equation? Also, does a negative sign in front of the mystery5 method call in the first two if statements indicate that there will be a positive x value if -23 is inserted into the method call (Ex: -mystery5(-23, -48))?
public int mystery5(int x, int y){
if (x < 0) {
return -mystery5(-x, y);
} else if (y < 0) {
return -mystery5(x, -y);
} else if (x == 0 && y == 0) {
return 0;
} else {
return 100 * mystery5(x / 10, y / 10) + 10 * (x % 10) + y % 10;
}
}
So it looks to me that mystery5(1, 0) returns 1. Assuming that is correct, then the call mystery5(-1, 0) would hit that first statement and it would see that x = -1) which is less than zero. This does return -mystery5(-x,y), so when the values for x and y are put in, this is equivalent to return -mystery5(1,0). The - in front of mystery5 flips the sign on the result of the mystery5 function when called. So when mystery5(1,0) returns a 1, that gets negated to -1. And that is the final return value of mystery5(-1,0).

Tail v. Head Recursion

I was wondering if you would identify this as a head or tail recursive function:
int exponentiation(int x, int y){
if(!y) { return 1; }
return y > 1 ? x * exponentiation(x, y-1) : x;
}
This is not a tail recursion: returning the result of exponentiation is not the last action taken by the function; the multiplication by x is.
However, the function is easy to convert to a tail-recursive implementation by adding an extra parameter, exp:
int exponentiation_tail(int x, int y, int exp = 1){
if(y <= 0) { return exp; }
return exponentiation_tail(x, y-1, exp*x);
}

type of a function in D

I'm interested in creating a function Derivative that returns a function that is the derivative of some function that is passed to it, at some point. However, I want to be able to specialize this so that, for specific functions, I can return the analytical solution.
So, I'm looking for something like this:
auto Derivate(alias Function)(x)
{ return (Function(x+h) - Function(x-h))/(2h);}
auto Derivate(BSpline!(k)(x))(x)
{ return k * BSpline!(k-1)(x) + x * BSpline!(k-1)(x); }
However, I currently have BSpline defined this way:
pure Real BSpline(int k : 0, Real)(scope Real x, scope const(Real)[] t)
{
if (t[0] <= x && x < t[k+1])
return 1;
else
return 0;
}
pure Real BSpline(int k, Real)(scope Real x, scope const(Real)[] t)
{
if (t[0] <= x && x < t[k+1])
{
Real a = (x - t[0]) / (t[k] - t[0]);
Real b = (t[k+1] - x) / (t[k+1] - t[1]);
Real c = BSpline!(k-1,Real)(x, t[0..k+1]);
Real d = BSpline!(k-1,Real)(x, t[1..k+2]);
Real rv = (c?c*a:c) + (d?d*b:d);
return rv;
}
else
return 0;
}
So the type signature on BSpline is going to be Real function(Real,Real), which isn't differentiable from any other kind of function. Is the way to solve this to create a "BSpline" class with opCall defined? Or can I do some sort of typedef to identify this function?
Thanks!
To specialize a template, you have to use the : notation:
auto foo(alias F_, X_)(X_ x) {
/* code here ... */
}
auto foo(alias F_ : BSpline, X_)(X_ x) {
/* specialized version here */
}

What is the most efficient way to calculate the least common multiple of two integers?

What is the most efficient way to calculate the least common multiple of two integers?
I just came up with this, but it definitely leaves something to be desired.
int n=7, m=4, n1=n, m1=m;
while( m1 != n1 ){
if( m1 > n1 )
n1 += n;
else
m1 += m;
}
System.out.println( "lcm is " + m1 );
The least common multiple (lcm) of a and b is their product divided by their greatest common divisor (gcd) ( i.e. lcm(a, b) = ab/gcd(a,b)).
So, the question becomes, how to find the gcd? The Euclidean algorithm is generally how the gcd is computed. The direct implementation of the classic algorithm is efficient, but there are variations that take advantage of binary arithmetic to do a little better. See Knuth's "The Art of Computer Programming" Volume 2, "Seminumerical Algorithms" § 4.5.2.
Remember
The least common multiple is the least whole number that is a multiple of each of two or more numbers.
If you are trying to figure out the LCM of three integers, follow these steps:
**Find the LCM of 19, 21, and 42.**
Write the prime factorization for each number. 19 is a prime number. You do not need to factor 19.
21 = 3 × 7
42 = 2 × 3 × 7
19
Repeat each prime factor the greatest number of times it appears in any of the prime factorizations above.
2 × 3 × 7 × 19 = 798
The least common multiple of 21, 42, and 19 is 798.
I think that the approach of "reduction by the greatest common divider" should be faster. Start by calculating the GCD (e.g. using Euclid's algorithm), then divide the product of the two numbers by the GCD.
Best solution in C++ below without overflowing
#include <iostream>
using namespace std;
long long gcd(long long int a, long long int b){
if(b==0)
return a;
return gcd(b,a%b);
}
long long lcm(long long a,long long b){
if(a>b)
return (a/gcd(a,b))*b;
else
return (b/gcd(a,b))*a;
}
int main()
{
long long int a ,b ;
cin>>a>>b;
cout<<lcm(a,b)<<endl;
return 0;
}
First of all, you have to find the greatest common divisor
for(int i=1; i<=a && i<=b; i++) {
if (i % a == 0 && i % b == 0)
{
gcd = i;
}
}
After that, using the GCD you can easily find the least common multiple like this
lcm = a / gcd * b;
I don't know whether it is optimized or not, but probably the easiest one:
public void lcm(int a, int b)
{
if (a > b)
{
min = b;
max = a;
}
else
{
min = a;
max = b;
}
for (i = 1; i < max; i++)
{
if ((min*i)%max == 0)
{
res = min*i;
break;
}
}
Console.Write("{0}", res);
}
Here is a highly efficient approach to find the LCM of two numbers in python.
def gcd(a, b):
if min(a, b) == 0:
return max(a, b)
a_1 = max(a, b) % min(a, b)
return gcd(a_1, min(a, b))
def lcm(a, b):
return (a * b) // gcd(a, b)
Using Euclidean algorithm to find gcd and then calculating the lcm dividing a by the product of gcd and b worked for me.
int euclidgcd(int a, int b){
if(b==0)
return a;
int a_rem = a % b;
return euclidgcd(b, a_rem);
}
long long lcm(int a, int b) {
int gcd=euclidgcd(a, b);
return (a/gcd*b);
}
int main() {
int a, b;
std::cin >> a >> b;
std::cout << lcm(a, b) << std::endl;
return 0;
}
Take successive multiples of the larger of the two numbers until the result is a multiple of the smaller.
this might work..
public int LCM(int x, int y)
{
int larger = x>y? x: y,
smaller = x>y? y: x,
candidate = larger ;
while (candidate % smaller != 0) candidate += larger ;
return candidate;
}
C++ template. Compile time
#include <iostream>
const int lhs = 8, rhs = 12;
template<int n, int mod_lhs=n % lhs, int mod_rhs=n % rhs> struct calc {
calc() { }
};
template<int n> struct calc<n, 0, 0> {
calc() { std::cout << n << std::endl; }
};
template<int n, int mod_rhs> struct calc<n, 0, mod_rhs> {
calc() { }
};
template<int n, int mod_lhs> struct calc <n, mod_lhs, 0> {
calc() { }
};
template<int n> struct lcm {
lcm() {
lcm<n-1>();
calc<n>();
}
};
template<> struct lcm<0> {
lcm() {}
};
int main() {
lcm<lhs * rhs>();
}
Euclidean GCD code snippet
int findGCD(int a, int b) {
if(a < 0 || b < 0)
return -1;
if (a == 0)
return b;
else if (b == 0)
return a;
else
return findGCD(b, a % b);
}
Product of 2 numbers is equal to LCM * GCD or HCF. So best way to find LCM is to find GCD and divide the product with GCD. That is, LCM(a,b) = (a*b)/GCD(a,b).
There is no way more efficient than using a built-in function!
As of Python 3.8 lcm() function has been added in math library. And can be called with folowing signature:
math.lcm(*integers)
Returns the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without arguments returns 1.
Extending #John D. Cook answer that is also marked answer for this question. ( https://stackoverflow.com/a/3154503/13272795), I am sharing algorithm to find LCM of n numbers, it maybe LCM of 2 numbers or any numbers. Source for this code is this
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Returns LCM of array elements
ll findlcm(int arr[], int n)
{
// Initialize result
ll ans = arr[0];
// ans contains LCM of arr[0], ..arr[i]
// after i'th iteration,
for (int i = 1; i < n; i++)
ans = arr[i] * ans/gcd(arr[i], ans);
return ans;
}
Since we know the mathematic property which states that "product of LCM and HCF of any two numbers is equal to the product of the two numbers".
lets say X and Y are two integers,
then
X * Y = HCF(X, Y) * LCM(X, Y)
Now we can find LCM by knowing the HCF, which we can find through Euclidean Algorithm.
LCM(X, Y) = (X * Y) / HCF(X, Y)
Hope this will be efficient.
import java.util.*;
public class Hello {
public static int HCF(int X, int Y){
if(X == 0)return Y;
return HCF(Y%X, X);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int X = scanner.nextInt(), Y = scanner.nextInt();
System.out.print((X * Y) / HCF(X, Y));
}
}
Yes, there are numerous way to calculate LCM such as using GCD (HCF).
You can apply prime decomposition such as (optimized/naive) Sieve Eratosthenes or find factor of prime number to compute GCD, which is way more faster than calculate LCM directly. Then as all said above, LCM(X, Y) = (X * Y) / GCD(X, Y)
I googled the same question, and found this Stackoverflow page,
however I come up with another simple solution using python
def find_lcm(numbers):
h = max(numbers)
lcm = h
def check(l, numbers):
remainders = [ l%n==0 for n in numbers]
return all(remainders)
while (check(lcm, numbers) == False):
lcm = lcm + h
return lcm
for
numbers = [120,150,135,225]
it will return 5400
numbers = [120,150,135,225]
print(find_lcm(numbers)) # will print 5400

Binary math

If I know the number number y and know that 2^x=y, how do I compute x?
Base 2 logarithm function:
log2(y)
which is equivalent to:
log(y) / log(2)
for arbitrary base.
And in case you don't have a log function handy, you can always see how many times you must divide y by 2 before it becomes 1. (This assumes x is positive and an integer.)
If you are sure that it is a power of 2, then you can write a loop and right shift the number until you get a 1. The number of times the loop ran will be the value of x.
Example code:
int power(int num)
{
if(0 == num)
{
return 0;
}
int count = 0;
do
{
++count;
num = num >> 1;
}while(! (num & 1) && num > 0);
return count;
}
If x is a positive integer, then, following code will be more efficient..
unsigned int y; // You know the number y for which you require x..
unsigned int x = 0;
while (y >>= 1)
{
x++;
}
x is the answer!

Resources