He hecho un programa en Java que calcula potencias de dos, pero parece muy ineficiente. Para poderes más pequeños (2^4000, por ejemplo), lo hace en menos de un segundo. Sin embargo, estoy buscando calcular 2^43112609, que es uno mayor que el número primo conocido más grande. Con más de 12 millones de dígitos, tomará mucho tiempo ejecutarlo. Aquí está mi código hasta ahora:Cálculo de potencias extremadamente grandes de 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);
}
}
}
Esto no es para un proyecto escolar ni nada; solo por diversión. Cualquier ayuda en cuanto a cómo hacer que esto sea más eficiente sería apreciada. ¡Gracias!
Kyle
P.S. No mencioné que la salida debería estar en base-10, no en binario.
representación binaria es muy fácil: 1000 ... 00 :) no solo quiere calcular 2^N sino que imprime como decimal, ¿verdad? – Andrey
buena tarea de Project Euler :) – Andrey