- 问题描述
求出区间[a,b]中所有整数的质因数分解。 - 输入说明
输入两个整数a,b。
2<=a<=b<=10000
- 输出说明
每行输出一个数的分解,形如k=a1a2a3...(a1<=a2<=a3...,k也是从小到大的)(具体可看范例) - 输入范例
cpp
3 10
- 输出范例
cpp
3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5
感想:如果是合数的话,得分解到最后一个数是质数。
代码如下:
cpp
#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n) {
if(n<2) return false;
if(n==2) return true;
if(n%2==0) return false;
for(int i = 3; i*i<=n; i+=2)
if(n%i==0)
return false;
return true;
}
int main() {
int a,b;
cin>>a>>b;
for(int i = a; i<=b; ++i) {
int temp = i;
if(isPrime(temp))
cout<<temp<<"="<<temp;
else {
cout<<temp<<"=";
bool single = true;
for(int j = 2; j*j<=i; ++j) {
if(temp%j==0) {
if(!single) cout<<"*";
cout<<j;
temp=temp/j;
j=1;
single = false;
if(isPrime(temp)){
cout<<"*"<<temp;
break;
}
}
}
}
cout<<endl;
}
return 0;
}