You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SML代码为何触发Overflow错误?求修复方案

Hey there! Let's figure out why you're hitting that Overflow error and get your SML code fixed up.

What's Causing the Overflow?

The main issue is your prime function doesn't handle numbers ≤ 1. If you pass in 0, 1, or a negative number, it calls detPrime(num, 2). Since divn starts at 2 and keeps incrementing (it'll never equal num when num < 2), it just keeps adding 1 to divn until it exceeds the maximum value of SML's fixed-size int type—boom, Overflow error.

On top of that, your detPrime checks all divisors up to num itself, which is super inefficient for large numbers and makes hitting that integer limit even faster.

Fixing the Prime Check

Let's rewrite the prime functions to handle edge cases and optimize the checks:

(* Helper to check primality, stops at sqrt(num) to save time *)
fun detPrime(num:int, divn:int) =
    if divn * divn > num then true  (* No divisors found up to sqrt(num) = prime *)
    else if num mod divn = 0 then false  (* Found a divisor = not prime *)
    else detPrime(num, divn + 1);

fun prime(num: int) =
    if num <= 1 then false  (* Numbers ≤1 aren't primes *)
    else if num = 2 then true  (* 2 is the only even prime *)
    else if num mod 2 = 0 then false  (* Even numbers >2 can't be prime *)
    else detPrime(num, 3);  (* Start checking odd divisors from 3 *)

Here's what we improved:

  • We immediately rule out non-primes like 0, 1, and even numbers >2, which stops the infinite recursion that caused overflow.
  • detPrime stops checking at the square root of num instead of all the way to num—this cuts down on recursion depth a ton for large primes.

Finishing the Goldbach Function

Your goldbachHelp code was cut off, but since you're working on Goldbach's conjecture (expressing even numbers as the sum of two primes), here's the complete implementation:

fun goldbachHelp(num1: int, num2: int) =
    if num2 > num1 then []  (* Fallback (shouldn't trigger for even nums ≥4) *)
    else if prime(num2) andalso prime(num1) then [num2, num1]
    else goldbachHelp(num1 - 1, num2 + 1);

fun goldbach(num: int) =
    if num < 4 orelse num mod 2 <> 0 then []  (* Goldbach only applies to even nums ≥4 *)
    else goldbachHelp(num - 2, 2);

Test It Out

Try these examples to make sure it works:

  • goldbach(4) → [2,2]
  • goldbach(10) → [3,7]
  • prime(23) → true, prime(24) → false

This should get rid of that Overflow error and make your code work as intended.

内容的提问来源于stack exchange,提问作者Michael Mackay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:12:24