博客
关于我
算法笔记_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 CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>
MySQL DBA 进阶知识详解
查看>>
Mura CMS processAsyncObject SQL注入漏洞复现(CVE-2024-32640)
查看>>
Mysql DBA 高级运维学习之路-DQL语句之select知识讲解
查看>>
mysql deadlock found when trying to get lock暴力解决
查看>>
MuseTalk如何生成高质量视频(使用技巧)
查看>>
mutiplemap 总结
查看>>
MySQL DELETE 表别名问题
查看>>
MySQL Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>
MySQL FEDERATED 提示
查看>>
mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
查看>>
Mysql group by
查看>>
MySQL I 有福啦,窗口函数大大提高了取数的效率!
查看>>
mysql id自动增长 初始值 Mysql重置auto_increment初始值
查看>>