功能:输入一个数 然后进行因式分解 例如:90=2*3*3*5
c++代码:
#include<bits/stdc++.h> using namespace std; int main(){ long num; while(cin>>num){ long value=num,t=1; for(int i=2;i<=num;++i){ while(num%i==0) { t*=i; cout<<i<<(t==value? "":"*"); num=num/i; } } cout<<"="<<value<<endl; } return 0; }
改进后的c++代码:(在效率上较上个版本提高了不少)
#include<bits/stdc++.h> using namespace std; int main(){ long num; while(cin>>num){ long value=num,t=1; if(value==1){ cout<<"1=1 "; continue; } for(int i=2;i<=sqrt(num);++i){ while(num%i==0) { t*=i; cout<<i<<(t==value? "":"*"); num=num/i; } if(num<=1) break; } if(num>1) cout<<num; cout<<"="<<value<<endl; } return 0; }