编程大题
花朵数
题目
一个N位的十进制正整数,如果它的每个位上的数字的N次方的和等于这个数本身,则称其为花朵数。
例如:当 N=3
时,153
就满足条件,因为1^3+5^3+3^3=153
,这样的数字也被称为水仙花数(其中,“^”表示乘方,5^3表示5的3次方,也就是立方)。
当N=4
时,1634
满足条件,因为1^4+6^4+3^4+4^4=1634
。
当N=5
时,92727
满足条件。
实际上,对N的每个取值,可能有多个数字满足条件。
程序的任务是:求N=21
时,所有满足条件的花朵数。注意:这个整数有21位,它的各个位数字的21次方之和正好等于这个数本身。
如果满足条件的数字不只有一个,请从小到大输出所有符合条件的数字,每个数字占一行。因为这个数字很大,请注意解法时间上的可行性。要求程序在1分钟内运行完毕。
参考答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import java.math.BigInteger;
public class Test1 { public static void main(String[] args) { long start = System.currentTimeMillis(); int[] a = new int[10]; BigInteger[] b = new BigInteger[10]; b[0] = BigInteger.ZERO; b[1] = BigInteger.ONE; for (int i = 2; i <= 9; i++) { b[i] = BigInteger.valueOf(i).pow(21); } ss(b, a, 0, 21); long end = System.currentTimeMillis(); double sec = (end - start) / 1000.0; System.out.println(sec + "秒"); } private static void ss(BigInteger[] b, int[] a, int index, int left) { if (index == 9) { a[9] = left; if (a[9] < 10) { BigInteger ret = BigInteger.ZERO; for (int i = 0; i < a.length; i++) { if (ret.toString().length() > 21) { ret = null; break; } if (a[i] != 0) { ret = ret.add(b[i].multiply(BigInteger.valueOf(a[i]))); } } if (ret != null && ret.toString().length() == 21) { String x = ret.toString(); int[] c = new int[10]; for (int i = 0; i < x.length(); i++) { c[x.charAt(i) - '0']++; } boolean isRight = true; for (int i = 0; i < c.length; i++) { if (a[i] != c[i]) { isRight = false; break; } } if (isRight) { System.out.println(x); } } } return; } for (int i = 0; i <= left; i++) { a[index] = i; ss(b, a, index + 1, left - i); } } }
|
程序运行参考结果
1 2
| 128468643043731391252 449177399146038697307
|