版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Selukwe/article/details/74992868
问题描述
求出区间[a,b]中所有整数的质因数分解。
输入格式
输入两个整数a,b。
输出格式
每行输出一个数的分解,形如k=a1*a2*a3...(a1<=a2<=a3...,k也是从小到大的)(具体可看样例)
样例输入
3 10
样例输出
3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5
提示
先筛出所有素数,然后再分解。
数据规模和约定
2<=a<=b<=10000
这题研究了很久。。先贴初版代码,写得很乱
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
int a, b;
int sum;
int isPrime(int a);
cin >> a >> b;
for (int i = a; i <= b; ++i)
{
cout << i << "=";
// 是素数
if (isPrime(i))
cout << i;
// 不是素数
else {
int temp = i;
sum = 1;
int x = 2;
while (sum != i)
for (int j = x; sum != i && j <= i / 2; ++j)
if (isPrime(j) && temp % j == 0)
{
sum *= j;
temp /= j;
cout << j;
if (sum != i)
cout << "*";
x = j;
break;
}
}
cout << endl;
}
return 0;
}
// 判断是否为素数,是就返回1,不是就返回0
int isPrime(int a)
{
const int False = 0;
const int True = 1;
int i;
if (a == 1)
return False;
for (i = 2; i <= sqrt(a); ++i)
if (a % i == 0)
return False;
return True;
}