给定数字N。任务是找到卢卡斯序列中存在的从1到N的数字总和。
卢卡斯数按以下整数顺序表示:
2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123 ......
例子:
Input : N = 10
Output : 17
Input : N = 5
Output : 10
方法:
- 遍历所有小于给定值N的卢卡斯数。
- 用0初始化sum变量。
- 继续添加这些卢卡斯数字以获得所需的总和。
下面是上述方法的实现:
C++
// C++ program to find sum of numbers from
// 1 to N which are in Lucas Sequence
#include
using namespace std;
// Function to return the
// required sum
int LucasSum(int N)
{
// Generate lucas number and keep on
// adding them
int sum = 0;
int a = 2, b = 1, c;
sum += a;
while (b <= N) {
sum += b;
int c = a + b;
a = b;
b = c;
}
return sum;
}
// Driver code
int main()
{
int N = 20;
cout << LucasSum(N);
return 0;
}
Java
// java program to find sum of numbers from
// 1 to N which are in Lucas Sequence
class GFG
{
// Function to return the
// required sum
static int LucasSum(int N)
{
// Generate lucas number and keep on
// adding them
int sum = 0;
int a = 2, b = 1, c;
sum += a;
while (b <= N) {
sum += b;
c = a + b;
a = b;
b = c;
}
return sum;
}
// Driver code
public static void main(String[] args)
{
int N = 20;
System.out.println(LucasSum(N));
}
// This code is contributed by princiraj1992
}
Python3
# Python3 program to find Sum of
# numbers from 1 to N which are
# in Lucas Sequence
# Function to return the
# required Sum
def LucasSum(N):
# Generate lucas number and
# keep on adding them
Sum = 0
a = 2
b = 1
c = 0
Sum += a
while (b <= N):
Sum += b
c = a + b
a = b
b = c
return Sum
# Driver code
N = 20
print(LucasSum(N))
# This code is contributed
# by mohit kumar
C#
// C# program to find sum of numbers from
// 1 to N which are in Lucas Sequence
using System;
class GFG
{
// Function to return the
// required sum
static int LucasSum(int N)
{
// Generate lucas number and keep on
// adding them
int sum = 0;
int a = 2, b = 1, c;
sum += a;
while (b <= N)
{
sum += b;
c = a + b;
a = b;
b = c;
}
return sum;
}
// Driver code
public static void Main(String[] args)
{
int N = 20;
Console.WriteLine(LucasSum(N));
}
}
// This code contributed by Rajput-Ji
PHP
输出:
46