• 递归之整数因子分解


    一、问题描述

    大于1的正整数n可以分解为n=x1*x2*...*xm.给定一个大于1的整数,然后统计其组成形式的个数,如输入12:

    12=12;     
    12=6*2;
    12=4*3;
    12=3*4;     12=3*2*2;
    12=2*6;     12=2*3*2;
    12=2*2*3;
    共8种不同的分解式。

    如输入10:

    10=10;

    10=5*2;

    10=2*5;

    共3种不同的分解式。

    二、问题分析

    从12的分解式可以看出,从12递减到2找12的因子,如果可以被整除,则将商作为新的值,继续寻找它的因子,直到不能再被分解,即为质数为止,所以本程序采用递归思想。

    三、程序设计

    #include<iostream>

    using namespace std;

    int count=1;               //从1开始计数,此时已经包含数字本身

    void out(int n);           //递归函数,函数声明

    void main()
    {
            int number;
            cout<<"Please input the number:"; 
            cin>>number;

            out(number);        //执行函数

            cout<<"共有的分解情况数:"<<count; 

            while(1);
    }

    //递归函数
    void out(int n)
    {
         for(int j=n-1;j>1;j--)  //从n-1递减到2,寻找约数
            if(n%j==0)
            {
                  count++;         //如果能被除尽,则加1
                  out(n/j);          //递归函数,将商继续进行递归
             }

    }

    四、程序结果

  • 相关阅读:
    快速排序
    归并排序
    堆排序
    通过先序和中序创建二叉树
    插入排序
    二叉排序树
    九宫重排
    字符串匹配 sunday算法
    傻逼数学题(math)
    最近点对学习笔记
  • 原文地址:https://www.cnblogs.com/cxmhy/p/4464104.html
Copyright © 2020-2023  润新知