循环结构(2)

版权声明:https://blog.csdn.net/huashuimu2003 https://blog.csdn.net/huashuimu2003/article/details/84502664

1.p1046质因子分解

给定一个整数n,将其分解成质因子连乘的形式。
样例输入 Sample Input

12

================
75
样例输出 Sample Output

12=2* 2*3

==================
75=3* 5*5
代码

#include<bits/stdc++.h>
using namespace std;
bool first=1;
bool prime(int k)
{
	for (long long i=2;i*i<=k;i++)
		if (k%i==0) return 0;
	return 1;
}
void print(int k)
{
	if (first)
	{
		cout<<k;
		first=0;
	}
	else cout<<'*'<<k;
}
int main()
{
	int n;
	scanf("%d",&n);
	cout<<n<<'=';
	for (int i=2;i<=n;i++)
		if (prime(i))
			for (;n%i==0;)
			{
				n/=i;
				print(i);
			}
	return 0;
}

2.p1049 cantor表

描述 Description
现代数学的著名证明之一是Georg Cantor证明了有理数是可枚举的。他是用下面这一张表来证明这一命题的:
1/1 1/2 1/3 1/4 1/5 …
2/1 2/2 2/3 2/4 …
3/1 3/2 3/3 …
4/1 4/2 …
5/1 …

我们以Z字形给上表的每一项编号。
第一项是1/1,然后是1/2,2/1,3/1,2/2,…
在这里插入图片描述
输入格式 Input Format
输入:整数N(1≤N≤10000000)
输出格式 Output Format
输出:表中的第N项
样例输入 Sample Input

7
样例输出 Sample Output

1/4
时间限制 Time Limitation
1s
代码

//算法分析:不难发现,每条斜线都有着不同的数字,第k条斜线则就会有k个数字,前n条斜线则有x(k)=1+2+3+··+k=1/2*k*(k+1)个数字.
//根据这个规律,很容易就可以知道第n个数字位于使得n<=x(k)且k最小的第k条斜线上的倒数第i=x(k)-n+1位置上,则其值为i/(k+1-i).
#include<stdio.h>
int main()
{
	int n,s,k;
	while(scanf("%d",&n)==1)
	{
		s=0;k=1;
		while(1)
		{
			s+=k;
			if(s>=n)
			{
				if(k%2==0) 
					printf("%d/%d\n",(k+1)-(s-n+1),s-n+1);
				else 
					printf("%d/%d\n",s-n+1,(k+1)-(s-n+1));
				break;
			}
			k++;
		}
	}
	return 0;
}

3.p1528 跑步训练

/*
*题目:详见haoi2013 
*算法:看备注 
*备注:注意:其实是可以用这个最大时间作为判断边界的。 
*/
#include<bits/stdc++.h>
using namespace std;
int M,T,t1,t2,t3;//
char ch;
int i;
int main()
{
	scanf("%d %d %d %d %d",&M,&T,&t1,&t2,&t3);
	for (i=1;i<=T;i++)
	{
		cin>>ch;
		if (ch=='f')
			M-=t2*2;
		else 
			M=M-t1-t3;
		if (M<0) break;
	}
	cout<<i-1<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/huashuimu2003/article/details/84502664