一本通————————1210 因子分解

【题目描述】

输入一个数,输出其素因子分解表达式。

【输入】

输入一个整数 n (2≤n<100)。

【输出】

输出该整数的因子分解表达式。

表达式中各个素数从小到大排列。

如果该整数可以分解出因子a的b次方,当b大于1时,写做 a^b ;当b等于1时,则直接写成a。

【输入样例】

60

【输出样例】

2^2*3*5

【来源】


No

 

题目如上。

解法一:非递归解法:

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

int main()
{
    int n,i,x,cnt;
    bool flag=true;
    cin>>n;

    while(n!=1)    
    {

        for(i=2; i<=n; i++)
        {
            cnt=0;        //用于记录幂次
            if(n%i==0)
            {
                x=i;
                cnt++;
                n=n/i;
                while(n%i==0)
                {
                    cnt++;
                    n=n/i;
                }
            }
            if(cnt!=0)
            {
                if(flag)        //用于控制*的输出
                    flag=false;
                else
                    cout<<"*";
                cout<<x;
                if(cnt!=1)
                {
                    cout<<"^"<<cnt;
                }
            }
            else
            {
                continue;
            }
        }
    }
    return 0;
}

 

解法二:递归解法

#include <bits/stdc++.h>
using namespace std;
bool flag=true;
int n;            //注意题目中的输入数据要写成全局变量
void f()
{
    if(n==1)
        return ;
    else
    {
        int cnt=0;
        for(int i=2; i<=n; i++)
        {
            if(n%i==0)
            {
                cnt++;
                n=n/i;
                while(n%i==0)
                {
                    cnt++;
                    n=n/i;
                }
                if(flag)
                    flag=false;
                else
                    cout<<"*";
                cout<<i;
                if(cnt!=1)
                {
                    cout<<"^"<<cnt;
                }
                f();
            }
        }
    }
    return ;
}

int main()
{

    cin>>n;
    f();
    return 0;
}

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九久呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值