博客
关于我
算法笔记_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 常见ALTER TABLE操作
查看>>
MySQL 常见的 9 种优化方法
查看>>
MySQL 常见的开放性问题
查看>>
Mysql 常见错误
查看>>
mysql 常见问题
查看>>
MYSQL 幻读(Phantom Problem)不可重复读
查看>>
mysql 往字段后面加字符串
查看>>
mysql 快速自增假数据, 新增假数据,mysql自增假数据
查看>>
Mysql 批量修改四种方式效率对比(一)
查看>>
Mysql 报错 Field 'id' doesn't have a default value
查看>>
MySQL 报错:Duplicate entry 'xxx' for key 'UNIQ_XXXX'
查看>>
Mysql 拼接多个字段作为查询条件查询方法
查看>>
mysql 排序id_mysql如何按特定id排序
查看>>
Mysql 提示:Communication link failure
查看>>
mysql 插入是否成功_PDO mysql:如何知道插入是否成功
查看>>
Mysql 数据库InnoDB存储引擎中主要组件的刷新清理条件:脏页、RedoLog重做日志、Insert Buffer或ChangeBuffer、Undo Log
查看>>
mysql 数据库中 count(*),count(1),count(列名)区别和效率问题
查看>>
mysql 数据库备份及ibdata1的瘦身
查看>>
MySQL 数据库备份种类以及常用备份工具汇总
查看>>