牛客 求数列第n项 斐波那契数列求和公式

题目描述
米兔从兔米那里了解到有一个无限长的数字序列 1, 2,3,3,4,4,4, 5,5,5,5,5 …,(已知此数列有一定规律,现将这些数字按不同数值堆叠,相同值的数字在同一层)。米兔想知道这个数字序列的第n个数所在的那一层之前的所有层里共有多少个数。
输入描述:

n(n<=1e18)

输出描述:

第n个数所在的那一层之前的所有层里共有多少个数

示例1
输入
复制

6

输出
复制

4





斐波那契数列

公式 :

F ( 1 ) = 1 , F ( 2 ) = 2 , F ( n ) = F ( n 1 ) + F ( n 2 ) <mtext>         </mtext> { n > = 2 } F(1) = 1, F(2)=2, F(n) = F(n-1)+F(n-2) ~~~~~~~\{n>=2\} F(1)=1,F(2)=2,F(n)=F(n1)+F(n2)       {n>=2}

求和公式

S ( n ) = 2 F ( n + 2 ) 1 S(n)=2F(n+2)-1 S(n)=2F(n+2)1

就本体而言,直接暴力

#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>

#define MAXN ((int)1e5+7)
#define ll long long
#define int long long
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;

#define show(x...) \ do { \ cout << "\033[31;1m " << #x << " -> "; \ err(x); \ } while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO{

	char print_f[105];
	void read() {}
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
		inline void read(T &x, T2 &... oth) {
			x = 0;
			char ch = getchar();
			ll f = 1;
			while (!isdigit(ch)) {
				if (ch == '-') f *= -1; 
				ch = getchar();
			}
			while (isdigit(ch)) {
				x = x * 10 + ch - 48;
				ch = getchar();
			}
			x *= f;
			read(oth...);
		}
	template <typename T, typename... T2>
		inline void print(T x, T2... oth) {
			ll p3=-1;
			if(x<0) putchar('-'), x=-x;
			do{
				print_f[++p3] = x%10 + 48;
			} while(x/=10);
			while(p3>=0) putchar(print_f[p3--]);
			putchar(' ');
			print(oth...);
		}
} // namespace FastIO
using FastIO::print;
using FastIO::read;

int n, m, Q, K;

string line;

signed main() {
#ifdef debug
	freopen("test", "r", stdin);
	clock_t stime = clock();
#endif
	cin >> n;
	int f[MAXN];
   	int level = 0, sum = 0;
	for(int i=1; i<=128; i++) {
		if(i == 1 || i == 2)
			f[1] = 1, f[2] = 1;
		else
			f[i] = f[i-1] + f[i-2];
		if(f[i]+sum >= n) { level = i; break; }
		sum += f[i];
	}
	if(n == 1 || n == 2) 
		cout << (n - 1) << endl;
	else
		cout << (sum) << endl;



#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}




全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务