水仙花数指一个 n 位数 (n≥3),它的每个数字的 n 次幂之和等于它本身。例如,$153$ 是一个水仙花数,因为 $1^3+5^3+3^3=153$。

下面是一个 Java 实现的水仙花算法:

public class NarcissisticNumber {
    public static void main(String[] args) {
        int n = 3; // n 位数
        for (int i = 0; i < Math.pow(10, n); i++) {
            int sum = 0;
            int temp = i;
            while (temp > 0) {
                int digit = temp % 10;
                sum += Math.pow(digit, n);
                temp /= 10;
            }
            if (sum == i) {
                System.out.println(i);
            }
        }
    }
}

这个算法的思路是,枚举所有的 n 位数,然后计算每个数的每个数字的 n 次幂之和。如果这个和等于这个数本身,那么这个数就是一个水仙花数,输出它即可。

注意,这个算法的时间复杂度是 $O(10^n)$,因为要枚举所有的 n 位数。当 n 很大时,这个算法会非常慢。可以通过其他优化方法来提高效率,比如只枚举一部分数,或者使用数学方法找到水仙花数的规律。


原文地址: http://www.cveoy.top/t/topic/2kO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录