例题5-7 丑数

【描述】
丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来,结果如
下:
1,2,3,4,5,6,8,9,10,12,15,…
求第1500个丑数。

【思路】
从小到大依次生成。
最基础的丑数是1,而后的所有丑数都是在这个基础上生成的。
如果按照正向思维分析,需要考虑除2,3,5以外的所有素数–这显然不切实际。

因此考虑派生的性质:假设一个丑数为x,那么2x,3x,5x也都是丑数。

这样,就可以使用一个优先队列保存所有已经生成的丑数,每次取出最小的丑数,以使密集生成三个新的丑数。

【代码】

//丑数,2x,3x,5x
#include<iostream>
#include<string>
#include<queue>
#include<set>
#include<vector>
#include<cstring>
using namespace std;
typedef long long LL;
const int coeff[3] = { 2,3,5 };
int main()
{	
	
	set<int>ss;
	priority_queue<LL, vector<LL>, greater<LL> >pq;
	pq.push(1);
	ss.insert(1);
	for (int i = 1;;i++)
	{
		LL x = pq.top();pq.pop();
		if (1500 == i) {
			cout << x << endl;
			break;
		}
		for (int j = 0;j < 3;j++)
		{
			LL t = x * coeff[j];
			if (!ss.count(t)) {
				pq.push(t);
				ss.insert(t);
			}
		}
	}
	return 0;
}
例题5-8 的情况可能是要求编写一个涉及财务记账的程序,使用函的方式来管理账户的收入、支出和查询余额。通常这样的例子会包含以下几个步骤: 1. **定义函**:首先,你可以定义一些函,比如 `deposit` (存款)、`withdraw` (取款) 和 `check_balance` (查询余额)。 ```python def deposit(account, amount): account.balance += amount print(f"存入了 {amount} 元,当前余额:{account.balance}") def withdraw(account, amount): if account.balance >= amount: account.balance -= amount print(f"取出了 {amount} 元,当前余额:{account.balance}") else: print("余额不足,无法取款") def check_balance(account): print(f"当前余额:{account.balance}") ``` 2. **创建对象**:然后创建一个表示账户的类(例如 `BankAccount`),存储余额作为属性。 ```python class BankAccount: def __init__(self, initial_balance=0): self.balance = initial_balance # 创建一个初始余额为0的账户实例 my_account = BankAccount() ``` 3. **调用函**:通过账户对象来使用这些函进行操作。 ```python deposit(my_account, 1000) withdraw(my_account, 500) check_balance(my_account) ``` 在这个例子中,多态并未直接体现,因为所有的函都是针对 `BankAccount` 对象设计的。但是,如果后续添加了其他类型的账户(如信用卡、储蓄账户等),并保持相同的函接口,那么就可以体现多态性——即不同类型的账户可以对同一组函有不同的响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值