좋아요. 제 친구 중 한 명이 저에게 준 도전 과제를 풀려고 노력하고 있습니다. 글쎄요, BigInteger
에서 마지막 9 자리를 자르려고했습니다. 잘 렸습니다. 처음 9 개가 너무 느리고 너무 오래 걸렸습니다.처음 9 자리 자르기
처음 9 개와 9 개가 필요한 이유는 BigInteger
이고 처음과 마지막은 pandigital입니다.
당신은 우리가 n = new BigInteger("123456789987654321")
잘 나가 "123456789"와 별도로은 "987654321"를 얻을 필요가 있다고 말은, 나는 그것이 매우 때문에이 문자열로의 BigInteger를 변환 할 NOT 을 이해하지 않는 경우 느린 과정.
여기서는 속도를 높이려고합니다.이 솔루션에 난처한 점이 있습니다. 황금 비율을 사용하는 것에 대해 들었습니다. 관심이 있다면 여기에 내 코드가 있습니다.
import java.math.BigInteger;
public class Main {
public static void main(String...strings)
{
long timeStart = System.currentTimeMillis();
fib(350_000);
long timeEnd = System.currentTimeMillis();
System.out.println("Finished processing, time: " + (timeEnd - timeStart) + " milliseconds.");
}
public static BigInteger fib(int n)
{
BigInteger prev1 = BigInteger.valueOf(0), prev2 = BigInteger.valueOf(1);
for (int i = 0; i < n; i++)
{
// TODO: Check if the head is pandigital as well.
BigInteger tailing9Digits = tailing9Digits(prev1);
boolean tailPandigital = isPanDigital(tailing9Digits);
if (tailPandigital)
{
System.out.println("Solved at index: " + i);
break;
}
BigInteger savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1.add(prev2);
}
return prev1;
}
public static BigInteger leading9Digits(BigInteger x)
{
// STUCK HERE.
return null;
}
public static BigInteger tailing9Digits(BigInteger x)
{
return x.remainder(BigInteger.TEN.pow(9));
}
static BigInteger[] pows = new BigInteger[16];
static
{
for (int i = 0; i < 16; i++)
{
pows[i] = BigInteger.TEN.pow(i);
}
}
static boolean isPanDigital(BigInteger n)
{
if (!n.remainder(BigInteger.valueOf(9)).equals(BigInteger.ZERO))
{
return false;
}
boolean[] foundDigits = new boolean[9];
boolean isPanDigital = true;
for (int i = 1; i <= 9; i++)
{
BigInteger digit = n.remainder(pows[i]).divide(pows[i - 1]);
for (int j = 0; j < foundDigits.length; j++) {
if (digit.equals(BigInteger.valueOf(j + 1)) && !foundDigits[j])
{
foundDigits[j] = true;
}
}
}
for (int i = 0; i < 9; i++)
{
isPanDigital = isPanDigital && foundDigits[i];
}
return isPanDigital;
}
}
로 빨리? – aa8y
하이 토마스, 정확하게 이해한다면 효율적/빠른 알고리즘을 사용하여 BigInteger의 처음 9 자리를 구할 수 있습니까? 나는 당신에게 도움이 필요한 것을 명시 적으로 언급 할 것을 제안합니다. 또한, 아마도 algo 등과 같은 태그를 포함 할 수도 있습니다. –
어제부터 질문을 다시하고있는 이유는 무엇입니까? http://stackoverflow.com/questions/15216777/splitting-bigintegers-digits –