zoukankan      html  css  js  c++  java
  • 水仙花数

     水仙花数(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 + "位的水仙花数:	");
    
                    // 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 + "	");
    			}
    		}
    		System.out.println();
    	}
    
    }
    
    	public static void main(String[] agrs) {
    		Narcissus();
    
    	}
    }
  • 相关阅读:
    iOS开发 如何检查内存泄漏
    iOS开发工具篇-AppStore统计工具
    10个必需的iOS开发工具和资源
    Eclipse的调试功能的10个小窍门[转]
    Eclipse远程调试应用程序
    MySQL学习笔记(二)
    Java内存回收机制基础[转]
    MySQL学习笔记(一)
    MySQL死锁[转]
    java编码规范
  • 原文地址:https://www.cnblogs.com/jeasion/p/10758332.html
Copyright © 2011-2022 走看看