简体   繁体   中英

Recursive function that returns the smallest divisor

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?

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) .

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

recursive method will throw StackOverflow exeption on relatively large prime number (eg 15331 ). non-recursive solution doesn't have such problem

public static int MinimalDivisor(int n)
{
    if ( n % 2 == 0)
        return 2;

    for(int d = 3; d < n/2; d=d+2)
        if (n % d == 0)
           return d;

    return n;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM