博客
关于我
算法笔记_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 数据库重置ID排序
查看>>
Mysql 数据类型一日期
查看>>
MySQL 数据类型和属性
查看>>
mysql 敲错命令 想取消怎么办?
查看>>
Mysql 整形列的字节与存储范围
查看>>
mysql 断电数据损坏,无法启动
查看>>
MySQL 日期时间类型的选择
查看>>
Mysql 时间操作(当天,昨天,7天,30天,半年,全年,季度)
查看>>
MySQL 是如何加锁的?
查看>>
MySQL 是怎样运行的 - InnoDB数据页结构
查看>>
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>
mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
查看>>
MYSQL 查看最大连接数和修改最大连接数
查看>>
MySQL 查看有哪些表
查看>>
mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
查看>>
MySql 查询以逗号分隔的字符串的方法(正则)
查看>>