[英]Recursive function that returns the smallest divisor
我寫了一個函數,遞歸計算整數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);
}
}
我的目標是構建一個遞歸函數,只接受整數n作為參數。 是否有任何可能的替代方法來避免調用另一個輔助函數作為參數整數n和d?
沒有必要使用2種方法就足夠了:
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);
}
參數d
是optinal,因為它的默認值為2
,您可以像SmallestDivisor(n)
一樣調用該方法。 如果你想要傳遞給方法的另一個d
值,只需調用SmallestDivisor(n,d)
。
更換
public static int SmallestDivisor(int n, int d)
同
public static int SmallestDivisor(int n, int d = 2)
為d
提供默認值並使此參數可選。 現在你可以調用SmallestDivisor(n)
或SmallestDivisor(n,3)
遞歸方法會將StackOverflow 15331
相對較大的素數(例如15331
)。 非遞歸解決方案沒有這樣的問題
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.