斯威夫特的阶乘 [英] Factorials in Swift

查看:87
本文介绍了斯威夫特的阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个很好的阶乘函数.我在这里写的那个完全可以工作,除非当n太大时.这是针对计算器应用程序的,对于无法分解的值,我可以返回0/0,因为我有一个错误检查器将其声明为不可能.但是,执行大量功能会使应用程序崩溃.我不能使用范围运算符,因为我的类型是双精度型.

I need a good factorial function. The one I have written here works entirely, except when n gets far too large. This is for a calculator app, and I can return 0 / 0 for values that cannot be factorialed because I have an error checker that will declare that as impossible. However performing the function on a very large number crashes the app. I can't use a range operator because my types are doubles.

func factorial(n: Double) -> Double {
    if n >= 0 {
        return n == 0 ? 1 : n * self.factorial(n - 1)
    } else {
        return 0 / 0
    }
}

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

正如其他人所说,您可以使用支持更大数字的库,或者只是不允许太大的值.

As others have said you can use libraries that support larger numbers, or just don't allow values that are too big.

请注意,如果要处理非常大的值,则可能需要使用循环而不是递归算法,因为递归会导致堆栈溢出.是的,没错,这样的同名崩溃".

Note that if you want to handle very large values you might need to use a loop rather than a recursive algorithm because recursion can cause a Stack Overflow. Yes, that's right, an SO "eponymous crash".

为防止数字太大,请找出不会崩溃的最大数字,并进行输入检查并拒绝大于该数字的数字.

To prevent numbers that are too big, figure out the largest number that doesn't crash, and do input checking and reject numbers bigger than that.

您可以通过相反的方向并每10步记录一次计数和结果来找出崩溃的数字:

You can figure out the number that crashes it by going in the opposite direction and logging the count and the result every 10 steps:

1 * 2 * 3 * 4 * 5 * 6 ...

1 * 2 * 3 * 4 * 5 * 6...

崩溃时,返回到先前的最大记录值,从此处开始插入先前记录的阶乘结果,然后一次执行步骤1,直到崩溃为止.然后只允许n小于崩溃值1.

When you crash, go back to the previous largest logged value, start from there plugging in your previously logged factorial result, and step 1 at a time until you crash. Then only allow n that's 1 less than your crash value.

这篇关于斯威夫特的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆