Jacobsthal numbers: Difference between revisions

Content added Content deleted
Line 1,641: Line 1,641:
=={{header|Java}}==
=={{header|Java}}==
<syntaxhighlight>
<syntaxhighlight>
import java.math.BigInteger;

public final class JacobsthalNumbers {

public static void main(String[] aArgs) {
System.out.println("The first 30 Jacobsthal Numbers:");
for ( int i = 0; i < 6; i++ ) {
for ( int k = 0; k < 5; k++ ) {
System.out.print(String.format("%15s", jacobsthalNumber(i * 5 + k)));
}
System.out.println();
}
System.out.println();
System.out.println("The first 30 Jacobsthal-Lucas Numbers:");
for ( int i = 0; i < 6; i++ ) {
for ( int k = 0; k < 5; k++ ) {
System.out.print(String.format("%15s", jacobsthalLucasNumber(i * 5 + k)));
}
System.out.println();
}
System.out.println();
System.out.println("The first 20 Jacobsthal oblong Numbers:");
for ( int i = 0; i < 4; i++ ) {
for ( int k = 0; k < 5; k++ ) {
System.out.print(String.format("%15s", jacobsthalOblongNumber(i * 5 + k)));
}
System.out.println();
}
System.out.println();
System.out.println("The first 10 Jacobsthal Primes:");
for ( int i = 0; i < 10; i++ ) {
System.out.println(jacobsthalPrimeNumber(i));
}
}
private static BigInteger jacobsthalNumber(int aIndex) {
BigInteger value = BigInteger.valueOf(parityValue(aIndex));
return BigInteger.ONE.shiftLeft(aIndex).subtract(value).divide(THREE);
}
private static long jacobsthalLucasNumber(int aIndex) {
return ( 1 << aIndex ) + parityValue(aIndex);
}
private static long jacobsthalOblongNumber(int aIndex) {
long nextJacobsthal = jacobsthalNumber(aIndex + 1).longValueExact();
long result = currentJacobsthal * nextJacobsthal;
currentJacobsthal = nextJacobsthal;
return result;
}
private static long jacobsthalPrimeNumber(int aIndex) {
BigInteger candidate = jacobsthalNumber(latestIndex++);
while ( ! candidate.isProbablePrime(CERTAINTY) ) {
candidate = jacobsthalNumber(latestIndex++);
}
return candidate.longValueExact();
}
private static int parityValue(int aIndex) {
return ( aIndex & 1 ) == 0 ? +1 : -1;
}
private static long currentJacobsthal = 0;
private static int latestIndex = 0;
private static final BigInteger THREE = BigInteger.valueOf(3);
private static final int CERTAINTY = 20;
}


</syntaxhighlight>
</syntaxhighlight>
{{ out }}
{{ out }}
<pre>
<pre>
The first 30 Jacobsthal Numbers:
0 1 1 3 5
11 21 43 85 171
341 683 1365 2731 5461
10923 21845 43691 87381 174763
349525 699051 1398101 2796203 5592405
11184811 22369621 44739243 89478485 178956971

The first 30 Jacobsthal-Lucas Numbers:
2 1 5 7 17
31 65 127 257 511
1025 2047 4097 8191 16385
32767 65537 131071 262145 524287
1048577 2097151 4194305 8388607 16777217
33554431 67108865 134217727 268435457 536870911

The first 20 Jacobsthal oblong Numbers:
0 1 3 15 55
231 903 3655 14535 58311
232903 932295 3727815 14913991 59650503
238612935 954429895 3817763271 15270965703 61084037575


The first 10 Jacobsthal Primes:
3
5
11
43
683
2731
43691
174763
2796203
715827883
</pre>
</pre>