Ho realizzato un programma in Java che calcola le potenze di due, ma sembra molto inefficiente. Per potenze più piccole (2^4000, diciamo), lo fa in meno di un secondo. Tuttavia, sto cercando di calcolare 2^43112609, che è maggiore del numero primo noto più grande. Con oltre 12 milioni di cifre, ci vorrà molto tempo per essere eseguito. Ecco il mio codice finora:Calcolo di potenze estremamente grandi di 2
import java.io.*;
public class Power
{
private static byte x = 2;
private static int y = 43112609;
private static byte[] a = {x};
private static byte[] b = {1};
private static byte[] product;
private static int size = 2;
private static int prev = 1;
private static int count = 0;
private static int delay = 0;
public static void main(String[] args) throws IOException
{
File f = new File("number.txt");
FileOutputStream output = new FileOutputStream(f);
for (int z = 0; z < y; z++)
{
product = new byte[size];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < b.length; j++)
{
product[i+j] += (byte) (a[i] * b[j]);
checkPlaceValue(i + j);
}
}
b = product;
for (int i = product.length - 1; i > product.length - 2; i--)
{
if (product[i] != 0)
{
size++;
if (delay >= 500)
{
delay = 0;
System.out.print(".");
}
delay++;
}
}
}
String str = "";
for (int i = (product[product.length-1] == 0) ?
product.length - 2 : product.length - 1; i >= 0; i--)
{
System.out.print(product[i]);
str += product[i];
}
output.write(str.getBytes());
output.flush();
output.close();
System.out.println();
}
public static void checkPlaceValue(int placeValue)
{
if (product[placeValue] > 9)
{
byte remainder = (byte) (product[placeValue]/10);
product[placeValue] -= 10 * remainder;
product[placeValue + 1] += remainder;
checkPlaceValue(placeValue + 1);
}
}
}
Questo non è per un progetto scolastico o altro; solo per il gusto di farlo. Sarebbe gradito qualsiasi aiuto su come rendere questo più efficiente! Grazie!
Kyle
P.S. Ho omesso di menzionare che l'output dovrebbe essere in base 10, non in binario.
La rappresentazione binaria è molto semplice: 1000 ... 00 :) non si desidera calcolare 2^N ma stampare come decimale, giusto? – Andrey
buon compito da Project Euler :) – Andrey