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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With