Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function that returns the smallest divisor

Tags:

c#

recursion

I wrote a function that computes recursively the smallest divisor of an integer n>1:

using System;                   
public class Program
{
    public static void Main()
    {
        int n = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(SmallestDivisor(n));
    }

    public static int SmallestDivisor(int n)
    {
        return SmallestDivisor(n, 2);
    }

    public static int SmallestDivisor(int n, int d)
    {
        if (n%d == 0)
            return d;
        else  
            return SmallestDivisor(n, d+1);
    }
}

My goal is to build a recursive function that takes only the integer n as an argument. Is there any possible alternative to avoid calling another auxiliary function taking as arguments integer n and d?

like image 771
FunnyBuzer Avatar asked Aug 22 '26 07:08

FunnyBuzer


2 Answers

There is no need for 2 method's one is just enough:

static void Main(string[] args)
{
    int n = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine(SmallestDivisor(n));
}

public static int SmallestDivisor(int n, int d=2)
{
    if (n % d == 0)
        return d;
    return SmallestDivisor(n, ++d);
}

The parameter d is optinal because it has a default value of 2 and you can call the method like SmallestDivisor(n). If you want another value of d passed to the method just call SmallestDivisor(n,d).

like image 92
Slaven Tojic Avatar answered Aug 23 '26 19:08

Slaven Tojic


replace

public static int SmallestDivisor(int n, int d)

with

public static int SmallestDivisor(int n, int d = 2)

To provide a default value for d and make this parameter optional. Now you can call SmallestDivisor(n) or SmallestDivisor(n,3)

Named and Optional Arguments

like image 34
fubo Avatar answered Aug 23 '26 19:08

fubo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!