目录
一、题目描述
循环输入,每输入一个正整数 n ( n ≤ 12 ) ,输出 1 × 2 × 3 × . . . × n 的值,当没有任何输入时,结束程序。
法一:迭代
代码如下:
#include "stdio.h"
int main()
{
int n,ans;
while(scanf("%d",&n)!=EOF)
{
ans=1;
while(n) //法一:迭代
{
ans*=n;
n--;
}
printf("%d\n",ans);
}
return 0;
}
法二:递归
代码如下:
#include "stdio.h"
int F(int n)
{
if(n<=1)return 1;
return n*F(n-1);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF) //法二:递归
{
printf("%d\n",F(n));
}
return 0;
}
二、课后习题
1.题目描述
方法:递归
思路:尾数为0,说明有10,说明因子有2*5
显然2比5多,5的个数就是尾数0的个数
代码如下:
int trailingZeroes(int n){
if(n==0)return 0;
return n/5+trailingZeroes(n/5);
}