从任一给定的正整数 n 出发,将其每一位数字相乘,记得到的乘积为 n1。以此类推,令 ni+1 为 ni 的各位数字的乘积,直到最后得到一个个位数 nm,则 m 就称为 n 的持续性。例如 679 的持续性就是 5,因为我们从 679 开始,得到 6×7×9=378,随后得到 3×7×8=168、1×6×8=48、4×8=32,最后得到 3×2=6,一共用了 5 步。
本题就请你编写程序,找出任一给定区间内持续性最长的整数。
输入格式:
输入在一行中给出两个正整数 a 和 b(1≤a≤b≤10^9 且 (b−a)<10^3),为给定区间的两个端点。
输出格式:
首先在第一行输出区间 [a,b] 内整数最长的持续性。随后在第二行中输出持续性最长的整数。如果这样的整数不唯一,则按照递增序输出,数字间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
500 700
输出样例:
5
679 688 697
代码长度限制16 KB
时间限制400 ms
内存限制64 MB
栈限制8192 KB
比赛中做的时候只写到了双重while,后面思路有点乱。
while(temp>9)
{
sum=1;
while(temp>0)
{
sum*=temp%10;
temp/=10;
}
temp=sum;
j++;
}
用了双while用max函数求出最大持续性,注意max函数的正确使用
maxx=max(maxx,j);
判断输出,当等于最大maxx的时候满足条件输出
int t=0;
for(int i=0;i<=b-a;i++)
{
if(!t)
{
if(pos[i]==maxx)
{
cout<<a+i;
t=1;
}
}
else if(pos[i]==maxx)
{
cout<<" "<<a+i;
}
}
return 0;
下面是完整代码
#include<bits/stdc++.h>
using namespace std;
int pos[1000000];
int main()
{
int minn=0;
int maxx=0;
int sum,j,k=0;
long long a,b;
cin>>a>>b;
for(int i=a;i<=b;i++)
{
int temp=i;
j=0;
while(temp>9)
{
sum=1;
while(temp>0)
{
sum*=temp%10;
temp/=10;
}
temp=sum;
j++;
}
maxx=max(maxx,j);
pos[k]=j;
k++;
}
cout<<maxx<<endl;
int t=0;
for(int i=0;i<=b-a;i++)
{
if(!t)
{
if(pos[i]==maxx)
{
cout<<a+i;
t=1;
}
}
else if(pos[i]==maxx)
{
cout<<" "<<a+i;
}
}
return 0;
}