算法竞赛入门——因子和阶乘

输入正整数n(2<=n<=100),吧阶乘n!=1*2*3*4*…*n分解诚因子想成的形式,
从小到大输出各个素数(2、3、/5…)的指数。例如825=3*5^2*11应该表示成(0,1,2,0,1),表示分别有0、1、2、0、1个2、3、5、7、11。你的程序应忽略比最大素因子更大的素数。
输入样例:
5
53
输出样例:
5!=3 1 1
53!=49 23 12 8 4 4 3 2 2 1 1 1 1 1 1 1

代码如下:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

using namespace std;

int is_prime(int x)
{
    for (int i = 2; i<=sqrt(x); i++)
        if (x%i == 0)
            return 0;
    return 1;
}

int main()
{
    int n, a[100], b[100];

    while (cin >> n)
    {
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));

        int Count = 0;
        for (int i = 2; i <= n; i++)
        {
            if (is_prime(i))
                a[Count++] = i;
        }
        for (int i = 1; i<=n; i++)
        {
            int m = i;
            for (int j = 0; j<Count; j++)
            {
                while (m%a[j] == 0)
                {
                    m /= a[j];
                    b[j]++;
                }
            }
        }
        cout << n << "!=";
        int x;
        for (x = Count; x >= 0; x--)
            if (b[x])
                break;
        for (int i = 0; i<=x; i++)
            cout << b[i] << " ";
        cout << endl;
    }

    system("pause");
    return 0;
}
我这里讲素数模板放到了while函数里面,无疑增加了运算量,因此,为减少运算量,直接将素数模板放到while函数外面,讲循环次数调整一下就可以。如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

using namespace std;

int is_prime(int x)
{
    for (int i = 2; i<=sqrt(x); i++)
        if (x%i == 0)
            return 0;
    return 1;
}

int main()
{
    int n, a[100], b[100];
    int Count = 0;
    for (int i = 2; i <= 100; i++)
    {
        if (is_prime(i))
            a[Count++] = i;
    }
    while (cin >> n)
    {
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        for (int i = 1; i<=n; i++)
        {
            int m = i;
            for (int j = 0; j<Count; j++)
            {
                while (m%a[j] == 0)
                {
                    m /= a[j];
                    b[j]++;
                }
            }
        }
        cout << n << "!=";
        int x;
        for (x = Count; x >= 0; x--)
            if (b[x])
                break;
        for (int i = 0; i<=x; i++)
            cout << b[i] << " ";
        cout << endl;
    }

    system("pause");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值