这个问题用循环估计解决不了了,除非搞个分布式集群服务器一起算,下面是我写的代码,其中对于算一个数的N次方的部分你可以参考一下,效率还是比较高的
MyThread类:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Hashtable;
public class MyThread implements Runnable {
private BigInteger start;
private BigInteger end;
private String fileName;
public MyThread(String start, String end, String fileName) {
this.start = new BigInteger(start);
this.end = new BigInteger(end);
this.fileName = "D:\\" + fileName;
}
private static long f(int a, int n) {
long result = 1;
while (n != 0) {
if ((n & 1) == 1) {
result = result * a;
}
a = a * a;
n = n >> 1;
}
return result;
}
public void run() {
Hashtable cf = new Hashtable();
for (int p = 0; p < 10; p++) {
BigInteger b1 = new BigInteger(f(p, 11) + "");
BigInteger b2 = new BigInteger(f(p, 10) + "");
BigInteger result = null;
result = b1.multiply(b2);
cf.put(p + "", result);
}
File f = new File(fileName);
if (!f.exists()) {
try {
f.createNewFile();
BufferedWriter output = new BufferedWriter(new FileWriter(f));
BigInteger ONE = new BigInteger("1");
BigInteger ZERO = new BigInteger("0");
BigInteger i = null;
for (i = start; i.compareTo(end) < 0; i = i.add(ONE)) {
String istr = i.toString();
int fn = istr.length();
BigInteger rel = ZERO;
for (int j = 1; j <= fn; j++) {
rel = rel.add(cf.get(istr.substring(j - 1, j)));
}
if (rel.compareTo(i) == 0) {
output.write(i.toString());
}
}
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Main
MyThread m1 = new MyThread("1二十个0","1二十个9","1.txt");
MyThread m2 = new MyThread("2二十个0","2二十个9","2.txt");
。。
Thread t1 = new Thread(m1);
Thread t2 = new Thread(m2);
。。
t1.start();
t2.start();
。。
写“二十个0”,因为直接写0说是不合法,不让发