`

poj 1338

 
阅读更多

题意:题目意思是求由2,3,5的乘积组成的数从大到小排列,从1开始,2,3,4,5,6,8,9,。。。

基本思想是设3个指针,分别表示3个素数乘到哪了,然后通过比较3个指针位置的递推结果来确定下一个数是什么。

代码如下:

#include <iostream>
using namespace std;

int a[1510];

int main()
{
	a[1]=1;
	int p2,p3,p5;
	p2=p3=p5=1;
	int n;
	for (int i=2;i<1500;i++)
	{
		int t2=a[p2]*2;
		int t3=a[p3]*3;
		int t5=a[p5]*5;
		if (t2<t3&&t2<t5)
		{
			a[i]=t2;
			p2++;
		} 
		else if (t3<t2&&t3<t5)
		{
			a[i]=t3;
			p3++;
		} 
		else if (t5<t2&&t5<t3)
		{
			a[i]=t5;
			p5++;
		} 
		else if (t2==t3&&t2<t5)
		{
			a[i]=t2;
			p2++;
			p3++;
		} 
		else if (t2==t5&&t2<t3)
		{
			a[i]=t2;
			p2++;
			p5++;
		} 
		else if (t3==t5&&t3<t2)
		{
			a[i]=t3;
			p3++;
			p5++;
		} 
		else
		{
			a[i]=t2;
			p2++;
			p3++;
			p5++;
		}
	}

	while (cin>>n&&n!=0)
	{
		cout<<a[n]<<endl;
	}
	return 0;


}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics