Home > Software engineering >  How to convert a growing recursive math function to code?
How to convert a growing recursive math function to code?

Time:09-29

static void Main(string[] args)
{
    var k0 = Convert.ToInt32(Console.ReadLine());
    var kn = Convert.ToInt32(Console.ReadLine());
    var result = Calculate(k0, kn);
}

private static double Calculate(int k0, int kn)
{
    var k1 = Math.Round(Math.Pow(Math.Sqrt(k0)   Math.Sqrt(Math.PI), 2)); // first iteration
    var k2 = Math.Round(Math.Pow(Math.Sqrt(k1)   Math.Sqrt(Math.PI), 2)); // 2nd iteration
    var k3 = Math.Round(Math.Pow(Math.Sqrt(k2)   Math.Sqrt(Math.PI), 2)); // 3rd iteration
    // calculate until kn
    return k3; // this should return kn
}

How should I change this code so it can recursively calculate until kn'th iteration?

CodePudding user response:

To avoid confusion, I don't think you're asking about recursive functions/methods that call themselves until some desired condition and then return a value.

This is easy enough using a for loop

private static double Calculate(int k0, int kn)
{
    double result = k0;
    for (var i = 0; i < kn; i  ){
        result = Math.Round(Math.Pow(Math.Sqrt(result)   Math.Sqrt(Math.PI), 2));
    }
    
    return result;
}

You could do this with recursion but in this case that would be overkill and it's not necessary.

CodePudding user response:

If you want a recursive solution:

private static double Calculate(int k0, int kn)
{
    return CalculateInternal(k0, kn, 1);
}

private static double CalculateInternal(int ki, int kn, int n)
{
    // Base case: exit when we've completed all iterations
    if (n > kn) return ki;
    
    // Current iteration
    var x = Math.Round(Math.Pow(Math.Sqrt(ki)   Math.Sqrt(Math.PI), 2));
    
    // Pass current iteration to next iteration
    return CalculateInternal(x, kn, n   1);
}

CodePudding user response:

Recursive which has the same signature, since you asked for it

private static double Calculate(int k, int n)
{
    return n == 0 ? k : Math.Round(Math.Pow(Math.Sqrt(Calculate(k, n - 1))   Math.Sqrt(Math.PI), 2));
}

CodePudding user response:

Well you could try to do this by adding in an optional argument.

private static double Calculate(int k0, int kn, int i = 0)
{
    if(i < kn)
    {
        return Calculate( Math.Round(Math.Pow(Math.Sqrt(k0)   Math.Sqrt(Math.PI), 2)) , kn,   i);
    }
    return k0;

}
  • Related