我需要考虑一个 64 位数字(n = pq)。所以我实现了一种方法,它依次搜索 [1; 范围内的所有数字;平方(n)]。
在具有 1,2 GHz 处理器的 Android 上执行需要 27 秒(不幸的是,我不知道 CPU 内核的数量)。所以我决定让它平行。好吧,两个Runnables
在 51 秒内给我结果,在 83 秒内给我 3 个结果。
我的程序除了在onCreate
.
final static private int WORKERS_COUNT = 3;
final static public int[] pqFactor(final long pq) {
stopFactorFlag = false;
long blockSize = (long)Math.ceil(Math.sqrt(pq) / WORKERS_COUNT);
ExecutorService executor = Executors.newFixedThreadPool(WORKERS_COUNT);
for (int workerIdx = 0; workerIdx < WORKERS_COUNT; ++workerIdx) {
Runnable worker = new FactorTask(pq, workerIdx * blockSize, (workerIdx + 1) * blockSize);
executor.execute(worker);
}
executor.shutdown();
try {
executor.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
private static boolean stopFactorFlag;
private static int p, q;
static private class FactorTask implements Runnable {
final private long pq;
private long leftBorder;
private long rightBorder;
public long pInternal;
public long qInternal;
/* Constructor was there */
@Override
public void run() {
for (qInternal = rightBorder; !stopFactorFlag && qInternal > leftBorder && qInternal > 1L; qInternal -= 2L) {
if (pq % qInternal == 0L) {
pInternal = pq / qInternal;
p = (int)pInternal;
q = (int)qInternal;
stopFactorFlag = true;
break;
}
}
}
}
PS这不是作业,我真的需要这个。也许是另一种方式。