九度OJ 1125:大整数的因子 (大数运算)

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:974

解决:494

题目描述:

已知正整数k满足2<=k<=9,现给出长度最大为30位的十进制非负整数c,求所有能整除c的k.

输入:

若干个非负整数c,c的位数<=30
每行一个c,当c=-1时中止
(不要对-1进行计算!)

输出:

每一个c的结果占一行
1) 若存在满足 c%k == 0 的k,输出所有这样的k,中间用空格隔开,最后一个k后面没有空格。
2) 若没有这样的k则输出"none"

样例输入:
30
72
13
-1
样例输出:
2 3 5 6
2 3 4 6 8 9
none
提示:

注意整数溢出问题
不要对-1进行计算

思路:

由于c最大是30位,可以拆成两个long long会比较简单一些。当然也可以直接按大整数除法来做。


代码:

#include <stdio.h>
#include <string.h>
 
int main(void)
{
    long long c[2];
    char s[31];
    int i, k, len;
    int find;
 
    while (scanf("%s", s) != EOF)
    {
        if (strcmp(s, "-1") == 0)
            break;
 
        len = strlen(s);
        c[0] = c[1] = 0; //c[0] high, c[1] low
        for (i=0; i<len-15; i++)
            c[0] = 10*c[0] + s[i]-48;
        for (i=len-15; i<len; i++)
        {
            if (i >= 0)
                c[1] = 10*c[1] + s[i]-48;
        }
        //printf("c[0]=%lld, c[1]=%lld\n", c[0], c[1]);
 
        find = 0;
        for (k=2; k<=9; k++)
        {
            long long tmp = 0;
            tmp = ((c[0])%k) * 1e15 + c[1];
            //printf("c[0]%%%d=%lld, tmp=%lld\n", k, (c[0])%k, tmp);
            if ( tmp % k == 0)
            {
                find ++;
                if (find > 1)
                    printf(" ");
                printf("%d", k);
            }
        }
        if (find == 0)
            printf("none");
        printf("\n");
    }
 
    return 0;
}
/**************************************************************
    Problem: 1125
    User: liangrx06
    Language: C
    Result: Accepted
    Time:20 ms
    Memory:912 kb
****************************************************************/



posted on 2015-10-24 10:28  梁山伯  阅读(318)  评论(0编辑  收藏  举报

导航