在某个范围内寻找最大的f(n)=n 其中f(n)为计算小于等于n的数值中含有“1”的总和
#include<iostream>
using namespace std;
pair<int,int> mypair;
int count_1(int n) //统计一个数值中含有“1”的个数
{
int sum=0;
while(n!=0)
{
if(n%10==1)
{
sum++;
}
n/=10;
}
return sum;
}
int f(int n) //<=n内的所有数值含有“1”的个数的总和
{
int sum=0;
while(n)
{
sum+=count_1(n);
n--;
}
return sum;
}
int main()
{
int maxcount=0;
int count=0;
int index=0;
for(int i=1;i<4000000000;i++) //寻找最大的f(n)=n
{
count=f(i);
if(count==i)
if(count>maxcount)
{
maxcount=count;
index=i;
}
}
if(maxcount==0&&index==0)
cout<<"没有符合的";
else
{
mypair=make_pair(maxcount,index);
cout<<"出现的最大的 1 的个数是"<<mypair.first<<"该值出现在"<<mypair.second<<endl;
}
return 0;
}