<MEMORY>Project Euler NO55

来源:互联网 发布:python while循环列表 编辑:程序博客网 时间:2024/05/29 13:10

我们将47与它的逆转相加,47 + 74 = 121, 可以得到一个回文。

并不是所有数都能这么快产生回文,例如:

349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337

也就是说349需要三次迭代才能产生一个回文。

虽然还没有被证明,人们认为一些数字永远不会产生回文,例如196。那些永远不能通过上面的方法(逆转然后相加)产生回文的数字叫做Lychrel数。因为这些数字的理论本质,同时也为了这道题,我们认为一个数如果不能被证明的不是Lychrel数的话,那么它就是Lychre数。此外,对于每个一万以下的数字,你还有以下已知条件:这个数如果不能在50次迭代以内得到一个回文,那么就算用尽现有的所有运算能力也永远不会得到。10677是第一个需要50次以上迭代得到回文的数,它可以通过53次迭代得到一个28位的回文:4668731596684224866951378664。

令人惊奇的是,有一些回文数本身也是Lychrel数,第一个例子是4994。

10000以下一共有多少个Lychrel数?


import java.util.ArrayList;import java.util.List;public class Problem55{public static void main(String[] args){long start = System.currentTimeMillis();System.out.print("answer:  ");howmany();long end = System.currentTimeMillis();System.out.print("time:  ");System.out.println(end - start);}static void howmany(){int nu = 0;for (int i = 1; i < 10000; i++){boolean ispo = false;int t = i;List<Integer> temp = new ArrayList<>();//用list,大数据while(t != 0){temp.add(t % 10);t /=10;}for (int j = 1; j <=50; j++){temp = add(temp);if (temp.size() == 0){ispo = true;break;}}if (!ispo){nu ++;//System.out.println(i);}}System.out.println(nu);}static List<Integer> add(List<Integer> array){List<Integer> arr = new ArrayList<>();int len = array.size();int temp = 0;for (int i = 0; i < len; i++){temp = array.get(i) + array.get(len - 1 - i) + temp;arr.add(temp % 10);temp /= 10;}if (temp != 0)//相加,不会出现temp为2位数;所以直接加{arr.add(temp);}List<Integer> arr0 = new ArrayList<>();for (int i = 0; i < len; i++){if (arr.get(i) != arr.get(arr.size() - 1 - i)){//前后交换下for (int j = arr.size() - 1; j >= 0; j--){arr0.add(arr.get(j));}return arr0;}}//返回 size 为0;说明是回文return arr0;}}


answer:  249
time:  86


0 0