试题 基础练习16 分解质因数

资源限制

时间限制:1.0s 内存限制:512.0MB

问题描述

求出区间[a,b]中所有整数的质因数分解。

输入格式

输入两个整数a,b。

输出格式

每行输出一个数的分解,形如k=a1a2a3…(a1<=a2<=a3…,k也是从小到大的)(具体可看样例)

样例输入

3 10

样例输出

3=3
4=22
5=5
6=2
3
7=7
8=222
9=33
10=2
5

提示

先筛出所有素数,然后再分解。

数据规模和约定

2<=a<=b<=10000

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<set>
#include<sstream>
#include<string>
#include<cmath>
#include<vector>

using namespace std;
int main()
{
    
    
	int a, b;
	vector<int> p_number;
	vector<int> result;
	cin >> a >> b;
	//筛选小于a的素数
	for (int i = 2; i < a; i++)
	{
    
    
		int t = 2;
		while (t <= sqrt(i) && i%t != 0)
			t++;
		if (i%t == 0 && i != t)
			continue;
		if (t > sqrt(i))
			p_number.push_back(i);
	}

	result.clear();
	for (int i = a; i <= b; i++)
	{
    
    
		int t = i;
		while (t > 0)
		{
    
    
			int j = 0;
			while (j < p_number.size() && t%p_number[j] != 0)
				j++;
			if (j >= p_number.size())
			{
    
    
			result.push_back(t);
			p_number.push_back(t);
			break;
			}
			else if (t%p_number[j] == 0)
			{
    
    
				result.push_back(p_number[j]);
				t = t / p_number[j];
				if (t == 1)
					t = 0;
			}
		}
		cout << i << "=";
		for (int i = 0; i < result.size() - 1; i++)
			cout << result[i] << "*";
		cout << result[result.size() - 1] << endl; //result.back() 蓝桥杯里编译有问题
		result.clear();
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39117858/article/details/104293350
今日推荐