forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSylvesterSequence.java
More file actions
50 lines (46 loc) · 1.54 KB
/
SylvesterSequence.java
File metadata and controls
50 lines (46 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.thealgorithms.recursion;
import java.math.BigInteger;
/**
* A utility class for calculating numbers in Sylvester's sequence.
*
* <p>Sylvester's sequence is a sequence of integers where each term is calculated
* using the formula:
* <pre>
* a(n) = a(n-1) * (a(n-1) - 1) + 1
* </pre>
* with the first term being 2.
*
* <p>This class is final and cannot be instantiated.
*
* @see <a href="https://en.wikipedia.org/wiki/Sylvester_sequence">Wikipedia: Sylvester sequence</a>
*/
public final class SylvesterSequence {
// Private constructor to prevent instantiation
private SylvesterSequence() {
}
/**
* Calculates the nth number in Sylvester's sequence.
*
* <p>The sequence is defined recursively, with the first term being 2:
* <pre>
* a(1) = 2
* a(n) = a(n-1) * (a(n-1) - 1) + 1 for n > 1
* </pre>
*
* @param n the position in the sequence (must be greater than 0)
* @return the nth number in Sylvester's sequence
* @throws IllegalArgumentException if n is less than or equal to 0
*/
public static BigInteger sylvester(int n) {
if (n <= 0) {
throw new IllegalArgumentException("sylvester() does not accept negative numbers or zero.");
}
if (n == 1) {
return BigInteger.valueOf(2);
} else {
BigInteger prev = sylvester(n - 1);
// Sylvester sequence formula: a(n) = a(n-1) * (a(n-1) - 1) + 1
return prev.multiply(prev.subtract(BigInteger.ONE)).add(BigInteger.ONE);
}
}
}