KY17 n的阶乘
输入一个整数n,输出n的阶乘(每组测试用例可能包含多组数据,请注意处理)
输入描述:
一个整数n(1=n=20)
输出描述:
n的阶乘
示例1
输入
3
输出
6
#include <iostream>
using namespace std;
//阶乘 f(n)=f(n-1)*n
//0!=1
long long factorial(int n){
if(n==0){
return 1;
} else{
return n* factorial(n-1);
}
}
int main() {
int n;
scanf("%d",&n);
printf("%lld",factorial(n));
return 0;
}
汉诺塔III
Problem Description
约19世纪末,在欧州的商店中出售一种智力玩具,在一块铜板上有三根杆,最左边的杆上自上而下、由小到大顺序串着由64个圆盘构成的塔。目的是将最左边杆上的盘全部移到右边的杆上,条件是一次只能移动一个盘,且不允许大盘放在小盘的上面。
现在我们改变游戏的玩法,不允许直接从最左(右)边移到最右(左)边(每次移动一定是移到中间杆或从中间移出),也不允许大盘放到下盘的上面。
Daisy已经做过原来的汉诺塔问题和汉诺塔II,但碰到这个问题时,她想了很久都不能解决,现在请你帮助她。现在有N个圆盘,她至少多少次移动才能把这些圆盘从最左边移到最右边?
Input
包含多组数据,每次输入一个N值(1<=N=35)。
Output
对于每组数据,输出移动最小的次数。
Sample Input
1 3 12
Sample Output
2 26 531440
#include <iostream>
using namespace std;
//汉诺塔问题
//n=n-1 f(n-1) A->C
//n=n 2
//n=1 A->B->C
long long Hanoi(int n){
if(n==1){
return 2;
} else{
return 3* Hanoi(n-1)+2;
}
}
int main() {
int n;
while (scanf("%d\n",&n)!=EOF){
printf("%lld\n",Hanoi(n));
}
return 0;
}
KY96 Fibonacci
The Fibonacci Numbers{0,1,1,2,3,5,8,13,21,34,55...} are defined by the recurrence: F0=0 F1=1 Fn=Fn-1+Fn-2,n=2 Write a program to calculate the Fibonacci Numbers.
输入描述:
Each case contains a number n and you are expected to calculate Fn.(0=n=30) 。
输出描述:
For each case, print a number Fn on a separate line,which means the nth Fibonacci Number.
示例1
输入
1
输出
1
#include <iostream>
using namespace std;
//分治思想 大问题分成若干个子问题
//Fn=Fn-1+Fn-2
//F0=0 F1=1
long long Fibonacci(int n){
if(n==0){
return 0;
} else if(n==1){
return 1;
} else{
return Fibonacci(n-1)+ Fibonacci(n-2);
}
}
int main() {
int n;
while (scanf("%d\n",&n)!=EOF){
printf("%lld\n",Fibonacci(n));
}
return 0;
}