Beatty Sequence in Java
The Beatty sequence, also known as the homogeneous Beatty sequence, is a set of integers that can be determined by taking the floor of all positive multiples of a positive irrational number.
The Nth term in the Beatty sequence can be obtained as:
T(i) = N * 2 ^ 0.2
Example 1:
Input:
int num = 4
Output:
The Beatty Sequence is 1, 2, 4, 5
Example 2:
Input:
int num = 5
Output:
The Beatty Sequence is 1, 2, 4, 5, 7
Approach: Using Square root method
The idea is to use a loop to iterate from 1 to N in order to identify the ith term in the sequence in which it involves square root.
Implementation:
FileName: BeattySequence.java
import java.io.*; import java.util.*; public class BeattySequence { static void Sequence(int num) { for(int i = 1; i <= num; i++) { // The Beatty sequence's first N terms are // obtained using this formula int result = (int)Math.floor(i * Math.sqrt(2)); System.out.print(result + ", "); } } public static void main(String args[]) { int num = 7; System.out.println("The Beatty Sequence is: "); Sequence(num); } }
Output:
The Beatty Sequence is: 1, 2, 4, 5, 7, 8, 9
Complexity Analysis:
The time complexity for the Beatty Sequence is given by O(n1/2), and the space complexity is given by O(1).