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

Java自守数判断程序异常:大于9376的数无法正确识别

问题分析与修复

你的程序在处理较大自守数时出错,核心原因有两个:

1. int类型溢出

当输入像90625这样的数时,copy*copy的结果(8212890625)远超Java int类型的最大值(2147483647),导致整数溢出,计算出错误的平方值,后续取模自然无法得到正确结果。

2. Math.pow的精度问题

Math.pow(10, ex)返回的是double类型,虽然小数值下能精确表示,但浮点数参与整数取模运算可能引入精度误差,进一步导致判断错误。


修复后的代码

将变量类型改为long避免溢出,同时用整数运算计算10的幂:

import java.util.Scanner;

public class AutomorphicChecker {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        long copy = n;
        int ex = 0;
        long temp = n;
        
        // 计算数字的位数
        while (temp != 0) {
            temp /= 10;
            ex++;
        }
        
        // 计算10的ex次方,用long类型避免精度问题
        long powerOf10 = 1;
        for (int i = 0; i < ex; i++) {
            powerOf10 *= 10;
        }
        
        // 判断自守数
        if ((copy * copy) % powerOf10 == copy) {
            System.out.println(copy + " is an automorphic number.");
        } else {
            System.out.println(copy + " is not an automorphic number.");
        }
        sc.close();
    }
}

测试验证

输入90625时,输出:

90625 is an automorphic number.

输入9376时,输出:

9376 is an automorphic number.

输入5、25、76等小自守数也能正确判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:25:22