1006: 【基础】质因子(1080)

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:61 解决:37

题目描述

任意输入一正整数 lns="http://www.w3.org/1998/Math/MathML"> ,求出它的所有质因子。如:lns="http://www.w3.org/1998/Math/MathML">102×5lns="http://www.w3.org/1998/Math/MathML">202×2×5

输入

输入只有一行,包括1个整数n (1<n<32768 )。

输出

输出若干行,按从小到大的顺序给出这个数的所有质因子,每行一个。

样例输入 复制

36

样例输出 复制

2
2
3
3

提示

n=int(input())
k=2
while True:
    if n==k:
        print(k)
        break
    elif n%k==0:
        print(k)
        n//=k
    else:
        k+=1

C/C++ 递归:

#include<bits/stdc++.h>
using namespace std;
void dfs(int n, int p){
    if(n==1) return;
    if(n%p== 0){
        cout<< p << endl;
		dfs(n/p,p); 
    }else{
        dfs(n,p+1); 
	}
}
int main(){
    int n;
    cin>>n;
    dfs(n,2);
	return 0;
}

C/C++ 循环:

#include<bits/stdc++.h>
using namespace std;
int n;
int main(){
    cin>>n;
    //在2~n的范围内找质因子 
    int k=2;
    while(n!=1){
    	if(n%k==0){
    		cout<<k<<endl;
    		n/=k;
		}else{
			k++;
		}
	}
	return 0;
}

C/C++ 自定义函数:

#include<bits/stdc++.h>
using namespace std;
int Decomposition(int x, int a[]){
 //分解 x,数组a升序记录所有质数
 //函数值返回分解出来的质数数量
    int cnt=0;
    int k=2;
    while(x!=1){
    	if(x%k==0){
    		a[++cnt]=k;
    		x/=k;
		}else{
			k++;
		}
	}    
    return cnt;
}
int main(){
    int n,a[110];
    cin>>n;
    int s=Decomposition(n,a);
    for(int i=1;i<=s;i++) {
    	cout<<a[i]<<endl;
	}
	return 0;
}