Swift while 循环中的非法硬件指令

Swift illegal hardware instruction in while loop

我试图在 Swift 中解决 Project Euler 的第 25 个(https://projecteuler.net/problem=25)问题,当我在 while 循环中更改我的条件时收到了一条非常神秘的错误消息。

起初,我从 2 开始,然后是 10,并得到了正确的结果。但是当输入 100 时,程序崩溃了。

var index = 3
var a = 1
var b = 2

while String(b).characters.count < 100 {
  let temp = b
  b = a + b
  a = temp
  index += 1
}

print(index)

这是错误:

0  swift                    0x00000001103b24f7 PrintStackTraceSignalHandler(void*) + 39
1  swift                    0x00000001103b19a6 SignalHandler(int) + 646
2  libsystem_platform.dylib 0x00007fffb3a89b3a _sigtramp + 26
3  libswiftCore.dylib       0x0000000112d6a40d (anonymous namespace)::Sentinels + 12861
4  swift                    0x000000010dcfadcf llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) + 655
5  swift                    0x000000010dd009c3 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 707
6  swift                    0x000000010d1fdc69 swift::RunImmediately(swift::CompilerInstance&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, swift::IRGenOptions&, swift::SILOptions const&) + 3385
7  swift                    0x000000010d1d2622 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 50738
8  swift                    0x000000010d17fd6c main + 9052
9  libdyld.dylib            0x00007fffb387a235 start + 1
Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -interpret ./project-euler/025/problem025.swift -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -color-diagnostics -module-name problem025 
[1]    8705 illegal hardware instruction  ./project-euler/025/problem025.swift

有人知道为什么会这样吗?完全相同的代码在 Python 和 Ruby.

中运行流畅

您的算法是正确的,但问题是 Swift 64 位整数最多只能保存 9,223,372,036,854,775,807 的值,即 9.22e+18。无符号整数可以是原来的两倍大,但仍远未接近 1,000 位。 Decimal/NSDecimalNumber 最多可以得到 38 位数字,这仍然不够。

您可能想要 create/use 一个可以表示任意大整数的库。只需在互联网上搜索 "swift arbitrarily large integer" 或 "swift biginteger"。

那么你的例程将正确计算结果。

如果您的所有操作都是正面的,您可以使用 UInt64,它们看起来是这样。这可能会防止溢出,因为您将获得更长的射程。