递归法进行整数的因式分解

分治法解决因式分解的方法是:将一个数n从2到它本身(计数为i)依次求余,如果求余后的结果为0,则说明i是它的因子,然后再对n/i进行递归,直到n/i==1,停止递归。下面是具体的代码

//*/
#include <bits/stdc++.h>
using namespace std;

int cnt = 0 ; //对方案的计数
stack<int> s;  //创建一个int类型的栈

void write(){
    int e;
    stack<int> s1;
    
    //输出栈s,即n的因子,同时用栈s1中转
    while (!s.empty()){
        e=s.top();
        s1.push(e);
        cout<<e<<"  ";
        s.pop();
    }//while
    cout<<endl;
    
    //以s1为中转,s因子恢复
    while (!s1.empty()){
        e=s1.top();
        s.push(e);
        s1.pop();
    }//while
}//write
0
    if(n ==1){    //分解到1,获得1种方案,输出
        cnt++ ;
        write();
    }//if
 
    int i = 2 ;
    while (i<=n){
        if(n%i==0) {        //整除,i是因子
            s.push(i);        //入栈
            
            factorization(n/i); //对 n/i 进行因子分解
            
            s.pop();        //栈中的元素出栈
        }//if
        i++ ;
    }//while
}//factorization
 
int main(){
    int n ;
 
    cin>>n;
    cout<<endl;
 
    factorization(n) ;
    
    cout<<endl<<cnt;
 
    return 0 ;
}//main

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值