Beatty序列(或齐次Beatty序列)是通过取正无理数的正倍数的底数而找到的整数序列。
Beatty序列的第N个术语:
查找Beatty序列的N个项
给定整数N ,任务是打印Beatty序列的前N个项。
例子:
Input: N = 5
Output: 1, 2, 4, 5, 7
Input: N = 10
Output: 1, 2, 4, 5, 7, 8, 9, 11, 12,
方法:想法是使用循环从1迭代到N以找到序列项。这 Beatty序列的项由下式给出:
下面是上述方法的实现:
C++
// C++ implementation of the
// above approach
#include
using namespace std;
// Function to print the first N terms
// of the Beatty sequence
void BeattySequence(int n)
{
for (int i = 1; i <= n; i++) {
double ans = floor(i * sqrt(2));
cout << ans << ", ";
}
}
// Driver code
int main()
{
int n = 5;
BeattySequence(n);
return 0;
}
Java
// Java implementation of the
// above approach
import java.util.*;
class GFG{
// Function to print the first N terms
// of the Beatty sequence
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 + ", ");
}
}
// Driver code
public static void main(String args[])
{
int n = 5;
BeattySequence(n);
}
}
// This code is contributed by Code_Mech
Python3
# Python3 implementation of the
# above approach
import math
# Function to print the first N terms
# of the Beatty sequence
def BeattySequence(n):
for i in range(1, n + 1):
ans = math.floor(i * math.sqrt(2))
print(ans, end = ', ')
# Driver code
n = 5
BeattySequence(n)
# This code is contributed by yatin
C#
// C# implementation of the
// above approach
using System;
class GFG{
// Function to print the first N terms
// of the Beatty sequence
static void BeattySequence(int n)
{
for(int i = 1; i <= n; i++)
{
double ans = Math.Floor(i * Math.Sqrt(2));
Console.Write(ans + ", ");
}
}
// Driver code
public static void Main()
{
int n = 5;
BeattySequence(n);
}
}
// This code is contributed by Code_Mech
Javascript
输出:
1, 2, 4, 5, 7,
参考: https : //oeis.org/A001951