现在的位置: 首页 > 综合 > 正文

POJ-1365-Prime Land 解题报告

2018年04月21日 ⁄ 综合 ⁄ 共 1117字 ⁄ 字号 评论关闭

       分解质因数水题。题意:给出n按照唯一分解定理分解出的质因数和幂,请输出n-1分解后的质因数和幂,注意顺序。


       我的解题思路:只是输入不太方便而已,需要用字符串输入,一次输入一行,输入完以后就处理数据就行了。


       我的解题代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <algorithm>

using namespace std;

const int N = 10000;

int factor[N], power[N], fn;
int num;
char str[N];

void InitRead();

void DataProcess();

int FastPow(int base, int n);

void Factor(int x);

int main()
{
    while (fgets(str, sizeof(str), stdin) != NULL)
    {
        if (str[1] == '\0' && str[0] == '0') break;
        InitRead();
        DataProcess();
    }
    return 0;
}

void InitRead()
{
    fn = 0;
    num = 1;
    int len = strlen(str);
    int temp, tmp;
    for (int i=0; i<len; ++i)
    {
        if (isdigit(str[i]))
        {
            sscanf(&str[i], "%d", &temp);
            while (isdigit(str[i++]));
            sscanf(&str[i], "%d", &tmp);
            while (isdigit(str[++i]));
            num *= FastPow(temp, tmp);
        }
    }
    num--;
    return;
}

void DataProcess()
{
    Factor(num);
    for (int i=fn-1; i>=0; --i)
    {
        printf("%d %d%c", factor[i], power[i], i == 0 ? '\n' : ' ');
    }
    return;
}

int FastPow(int base, int n)
{
    int ans = 1;
    while (n)
    {
        if (n & 1) ans *= base;
        base *= base;
        n >>= 1;
    }
    return ans;
}

void Factor(int x)
{
    int cnt = (int)sqrt(x + 0.5) + 1;
    for (int i=2; i<cnt; ++i)
    {
        if (x % i == 0)
        {
            power[fn] = 0;
            while (x % i == 0)
            {
                x /= i;
                power[fn]++;
            }
            factor[fn++] = i;
        }
    }
    if (x > 1)
    {
        power[fn] = 1;
        factor[fn++] = x;
    }
    return;
}

抱歉!评论已关闭.