题目描述
李老师的lucky number 是3,5和7,他爱屋及乌,还把所有质因数只有3,5,7的数字认定为lucky number,比如9, 15, 21, 25等等。请聪明的你帮忙算一算小于等于x的lucky number有多少个?
输入数据
一个正整数 x ,3=<x<=1000000000000
输出数据
小于等于x的lucky number的个数
样例输入
49
样例输出
11
解题思路
- 维护一个vector容器 lucky_nums
lucky_nums 里存的是从小到大遍历到的lucky number - 容器初始化为: vector lucky_nums = {1};
- 设置三个指针 a,b,c,分别对指向的数字 乘以 3、5、7
- 取得到的三个数字中的最小值,加入到容器中
- 遍历结束条件:容器末尾大于输入的数据x
代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<long long> lucky_nums = {1}; //因为后续要做乘法 所以第一个初始化为1
long long x;
cin >> x;
int a, b, c;
a = b = c = 0; //初始化
while (1)
{
long long n3 = lucky_nums[a] * 3; //不断的对容器里之前的每个数 做乘法(3 5 7)运算
long long n5 = lucky_nums[b] * 5;//n3 n5 n7 分别记录着乘以 3 5 7 的结果
long long n7 = lucky_nums[c] * 7;
long long Min = min(min(n3, n5), n7);
if (Min == n3)
a++; //当前数值被记录,继续往后乘
if (Min == n5)
b++;
if (Min == n7)
c++;
if (Min > x)
break; //已找到解
if (Min != lucky_nums.back()) //去重
lucky_nums.push_back(Min);
}
cout << lucky_nums.size() - 1 << endl; //因为有1 的存在 所以记得 -1
system("pause");
return 0;
}
解题思路2
- 递归枚举所有可行解
- 要避免重复(保证添加因数时按某种顺序枚举,比如按从小到大)
代码2
#include <bits/stdc++.h>
using namespace std;
long long x, ans;
void force(long long now, long long c){
if(c > 7 || now * c > x)
return ;
//cout << now << endl;
ans++;
force(now * c, c);
force(now * c, c + 2);
force(now * c, c + 4);
}
int main(){
cin >> x;
force(1, 3);
force(1, 5);
force(1, 7);
cout << ans;
return 0;
}
若文章存在问题,还请各位大佬批评指正,共同进步!