P1028 數的計算

題目描述
我們要求找出具有下列性質數的個數(包含輸入的自然數n):

先輸入一個自然數n(n≤1000),然後對此自然數按照如下方法進行處理:

1.不作任何處理;

2.在它的左邊加上一個自然數,但該自然數不能超過原數的一半;

3.加上數後,繼續按此規則進行處理,直到不能再加自然數爲止.

輸入輸出格式
輸入格式:
1個自然數n(n≤1000)

輸出格式:
1個整數,表示具有該性質數的個數。

輸入輸出樣例
輸入樣例#1:
6
輸出樣例#1:
6
說明

滿足條件的數爲

6,16,26,126,36,136

這道題的規律可真是…推了很久沒推出來,題解的寫法也太聰明瞭。
n爲奇數時f[n]=f[n-1],n爲偶數時f[n]=f[n-1]+f[n/2]。

#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int n,f[1001];
	cin>>n;
	memset(f,0,sizeof(f));
	f[1]=1;
	for(int i=2;i<=n;i++)
	{
		
		f[i]=f[i-1];
		if(i%2==0)
			f[i]+=f[i/2];
	}
	cout<<f[n]<<endl;
   return 0;
}

祭奠一下我T了的代碼(T_T):

#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int cnt;
int count(int n)
{
	if(n==1)
		return cnt;
	cnt+=n/2;
	for(int i=n/2;i>=1;i--)
		count(i);
}
int main()
{
	int n;
	while(cin>>n)
	{
		cnt=0;
		count(n);
		cout<<cnt+1<<endl;
	}
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章