Beatty sequence
Last Updated :
26 Oct, 2021
Beatty sequence (or homogeneous Beatty sequence) is the sequence of integers found by taking the floor of the positive multiples of a positive irrational number.
The Nth term of the Beatty sequence:
Find the N terms of Beatty Sequence
Given an integer N, the task is to print the first N terms of the Beatty sequence.
Examples:
Input: N = 5
Output: 1, 2, 4, 5, 7
Input: N = 10
Output: 1, 2, 4, 5, 7, 8, 9, 11, 12,
Approach: The idea is to iterate from 1 to N using loop to find the term of the sequence. The term of the Beatty sequence is given by:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void BeattySequence( int n)
{
for ( int i = 1; i <= n; i++) {
double ans = floor (i * sqrt (2));
cout << ans << ", " ;
}
}
int main()
{
int n = 5;
BeattySequence(n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void BeattySequence( int n)
{
for ( int i = 1 ; i <= n; i++)
{
int ans = ( int )Math.floor(i * Math.sqrt( 2 ));
System.out.print(ans + ", " );
}
}
public static void main(String args[])
{
int n = 5 ;
BeattySequence(n);
}
}
|
Python3
import math
def BeattySequence(n):
for i in range ( 1 , n + 1 ):
ans = math.floor(i * math.sqrt( 2 ))
print (ans, end = ', ' )
n = 5
BeattySequence(n)
|
C#
using System;
class GFG{
static void BeattySequence( int n)
{
for ( int i = 1; i <= n; i++)
{
double ans = Math.Floor(i * Math.Sqrt(2));
Console.Write(ans + ", " );
}
}
public static void Main()
{
int n = 5;
BeattySequence(n);
}
}
|
Javascript
<script>
function BeattySequence( n) {
for ( let i = 1; i <= n; i++) {
let ans = parseInt( Math.floor(i * Math.sqrt(2)));
document.write(ans + ", " );
}
}
let n = 5;
BeattySequence(n);
</script>
|
Time Complexity: O(n1/2)
Auxiliary Space: O(1)
Reference: https://oeis.org/A001951
Share your thoughts in the comments
Please Login to comment...