博客
关于我
算法笔记_218:花朵数(Java)
阅读量:437 次
发布时间:2019-03-06

本文共 2688 字,大约阅读时间需要 8 分钟。

目录

 


1 问题描述

一个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次方之和正好等于这个数本身。

如果满足条件的数字不只有一个,请从小到大输出所有符合条件的数字,每个数字占一行。因为这个数字很大,请注意解法时间上的可行性。

 

 

 


2 解决方案

 以下代码实际测试要接近3分钟才能出结果,代码仅供参考~

1 import java.math.BigInteger; 2 import java.util.ArrayList; 3 import java.util.Collections; 4  5 public class Main { 6     public static ArrayList
set = new ArrayList
(); 7 public static BigInteger[] value = new BigInteger[10]; 8 public static int count = 0; 9 10 public BigInteger getPow(BigInteger n) {11 BigInteger result = BigInteger.ONE;12 for(int i = 1;i <= 21;i++)13 result = result.multiply(n);14 return result;15 }16 17 public boolean check(int[] A) {18 BigInteger temp = BigInteger.ZERO;19 for(int i = 0;i < 10;i++) {20 BigInteger k = new BigInteger(""+A[i]);21 temp = temp.add(value[i].multiply(k));22 }23 String s = "" + temp;24 if(s.length() != 21)25 return false;26 int[] B = new int[10];27 for(int i = 0;i < 21;i++) {28 int k = s.charAt(i) - '0';29 B[k]++;30 }31 for(int i = 0;i < 10;i++)32 if(A[i] != B[i])33 return false;34 return true;35 }36 37 public void dfs(int step, int sum, int[] A) {38 if(step == 10) {39 if(sum == 21 && check(A)) {40 BigInteger temp = BigInteger.ZERO;41 for(int i = 0;i < 10;i++) {42 BigInteger k = new BigInteger(""+A[i]);43 temp = temp.add(value[i].multiply(k));44 }45 if(!set.contains(temp))46 set.add(temp);47 count++;48 }49 return;50 } else {51 for(int i = 0;i <= 21 - sum;i++) {52 A[step] = i;53 dfs(step + 1, sum + i, A);54 }55 }56 }57 58 public static void main(String[] args) {59 Main test = new Main();60 for(int i = 0;i <= 9;i++) {61 BigInteger a = new BigInteger(""+i);62 value[i] = test.getPow(a);63 }64 int[] A = new int[10];65 test.dfs(0, 0, A);66 Collections.sort(set);67 for(int i = 0;i < set.size();i++)68 System.out.println(set.get(i));69 }70 }

 

运行结果:

128468643043731391252449177399146038697307

 

转载地址:http://oztyz.baihongyu.com/

你可能感兴趣的文章
MySQL 在并发场景下的问题及解决思路
查看>>
MySQL 基础架构
查看>>
MySQL 基础模块的面试题总结
查看>>
MySQL 备份 Xtrabackup
查看>>
mYSQL 外键约束
查看>>
mysql 多个表关联查询查询时间长的问题
查看>>
mySQL 多个表求多个count
查看>>
mysql 多字段删除重复数据,保留最小id数据
查看>>
MySQL 多表联合查询:UNION 和 JOIN 分析
查看>>
MySQL 大数据量快速插入方法和语句优化
查看>>
mysql 如何给SQL添加索引
查看>>
mysql 字段区分大小写
查看>>
mysql 字段合并问题(group_concat)
查看>>
mysql 字段类型类型
查看>>
MySQL 字符串截取函数,字段截取,字符串截取
查看>>
MySQL 存储引擎
查看>>
mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
查看>>
MySQL 存储过程参数:in、out、inout
查看>>
mysql 存储过程每隔一段时间执行一次
查看>>
mysql 存在update不存在insert
查看>>