到x星球旅行的游客都被发给一个整数,作为游客编号。
x星的国王有个怪癖,他只喜欢数字3,5和7。
国王规定,游客的编号如果只含有因子:3,5,7,就可以获得一份奖品。
我们来看前10个幸运数字是:
3 5 7 9 15 21 25 27 35 45
因而第11个幸运数字是:49
小明领到了一个幸运数字 59084709587505,他去领奖的时候,人家要求他准确地说出这是第几个幸运数字,否则领不到奖品。
请你帮小明计算一下,59084709587505是第几个幸运数字。
如果数据量不大可以直接使用下面方法解决,但是当幸运数太大时,无法解决。
#include "stdio.h"
int fun(long long temp)
{
if(temp%3!=0&&temp%5!=0&&temp%7!=0)
return 0;
if(temp%3==0)
temp=temp/3;
if(temp%5==0)
temp=temp/5;
if(temp%7==0)
temp=temp/7;
if(temp==3||temp==5||temp==7||temp==1)
return 1;
fun(temp);
}
int main()
{
long long temp=59084709587505,i;
int num=0;
for(i=3;i<=temp;i++)
{
if(fun(i)==1)
{
num=num+1;
}
}
printf("%d\n",num);
return 0;
}
当数据太大时的解决方案:
//思路:生成法 (使用集合)
#include <iostream>
#include <set>
using namespace std;
typedef long long LL;
const LL MAX = 59084709587505;
int main()
{
LL tou=1,tt;
int a[3]={3,5,7},i;
set <LL> s;
while(true)
{
for(i=0;i<3;i++)
{
tt=tou*a[i];
if(tt<=MAX)
{
s.insert(tt);
}
}
//set :: upper_bound()函数是预定义的函数,用于获取集合中任何元素的上限。
tou=*(s.upper_bound(tou));
if(tou>=MAX) break;
}
cout<<s.size()<<endl;
return 0;
}
类似问题:丑数等。