7-31 掉入陷阱的数字(含重难点注释)

在这里插入图片描述
输入样例:

5

输出样例:

1:16
2:22
3:13
4:13

#include <stdio.h>

int f(int x);

int main ()
{
	//x是输入的数,i是第i步,mem是第i步的时候x变成了多少 
	int x;
	scanf("%d",&x);
	int i=1;
	int mem=f(x);
	int count;
	//这一步不可漏掉,因为如果这个数一开始就是个陷阱数字,就要直接输出(题目虽然没有这个具体要求,但是会有一个测试点不能通过) 
	if(mem==x){
		;
	}
	else
	{
		do{
			//加一个变量为了方便比较前后的mem是不是相等,以便决定是否停止输出
			count=mem;
			printf("%d:%d\n",i,mem);
			i++;
			//调用了f函数,使mem变成下一个mem 
			mem=f(mem);
		}while(mem!=count);
	}	
	printf("%d:%d\n",i,mem);

	return 0;
}
//f(x)=f(x-1)*3+1的函数 
int f(int x){
	int sum=0;
	while(x>0){
		sum+=x%10;
		x/=10;
	}
	return sum*3+1;
	
}

猜你喜欢

转载自blog.csdn.net/nnnnnick/article/details/89816891
今日推荐