水仙花数

 水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)。

目前技术有限只想到了爆破,指定位数后从0~10^n进行遍历爆破,但当N>7时已经很吃力。

基本思想是指定位数后将每一位进行拆分,放入数组中,再进行相等比较

package Questiones;

import java.util.Arrays;
import java.util.Scanner;

public class TestNarcissus {

    static void Narcissus() {
	System.out.print("指定最大位数N:");
	Scanner input = new Scanner(System.in);
	int N = input.nextInt();
	input.close();

	for (int i = 1; i <= N; i++) { // 位数
		int[] nums = new int[i];
		System.out.print(i + "位的水仙花数:\t");

                // 10^(i-1) ~ 10^i
		for (int j = (int) Math.pow(10, i - 1); j < Math.pow(10, i); j++) { 
			
                    for (int j2 = 0; j2 < i; j2++) { // 拆分获取的数,获取每一位
			
                        // j/Math.pow(10,j2)%10是获取每位位数
                        nums[i - j2 - 1] = (int) (j / Math.pow(10, j2) % 10);
                 
			}
			
                        // System.out.println("nums:"+Arrays.toString(nums));
			int sum = 0;
			for (int j2 = 0; j2 < i; j2++) {
			    sum += (int) Math.pow(nums[j2], i);

			}
			if (sum == j) {
			    System.out.print(+sum + "\t");
			}
		}
		System.out.println();
	}

}

	public static void main(String[] agrs) {
		Narcissus();

	}
}

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务