我們將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