Fork me on GitHub

Uva 10392 - Factoring Large Numbers

Problem F:

Factoring Large Numbers

One of the central ideas behind much cryptography is that factoring large numbers is computationally intensive. In this context one might use a 100 digit number that was a product of two 50 digit prime numbers. Even with the fastest projected computers this factorization will take hundreds of years.

You don't have those computers available, but if you are clever you can still factor fairly large numbers.

 

Input

The input will be a sequence of integer values, one per line, terminated by a negative number. The numbers will fit in gcc's long long int datatype. You may assume that there will be at most one factor more than 1000000.

Output

Each positive number from the input must be factored and all factors (other than 1) printed out. The factors must be printed in ascending order with 4 leading spaces preceding a left justified number, and followed by a single blank line.

Sample Input

90
1234567891
18991325453139
12745267386521023
-1

Sample Output

    2
    3
    3
    5

    1234567891

    3
    3
    13
    179
    271
    1381
    2423

    30971
    411522630413


复制代码
#include<stdio.h>
#include<string.h>
#define MAXN 1000000
int prime[MAXN];
int flag[MAXN];

is_prime()
{
/*
    筛不超过1000000的素数(注意题目的提示 ; 
    You may assume that there will be at most one factor more than 1000000. )
    存储到prime数组中,并返回素数的个数 
*/
    int i, j, n = 0;
    memset(flag, 0, sizeof(flag));
    for(i=2; i<MAXN; ++i)
    {
        if(!flag[i])
        {
            prime[n++] = i;
            flag[i] = 1;
            for(j=i+i; j<MAXN; j+=i)
            flag[j] = 1;
        }
    }
    
    return n;
}

int main()
{

    int term, track, i, j;
    long long n;
    term = is_prime();
    
    while(scanf("%lld", &n) != EOF && n >= 0)
    {
        if(n == 0 || n == 1) 
        {//处理 n = 1 和 n = 0 特殊情况 
            printf("    1\n\n");
            continue;
        }
        for(track=i=0; n != 1 && n != 0 && i<term; ++i)
        {
            while(n%prime[i] == 0) 
            {
                flag[track++] = prime[i];
                n /= prime[i];
            }
        }
        for(i=0; i<track; ++i) printf("    %d\n", flag[i]);
        if(n != 1) printf("    %lld\n\n", n);
        else printf("\n");
    }
    
    return 0;
}
复制代码

解题思路:

刚开始肯定会觉得难求(这个看样例就知道了)但再回去看一遍题目的时候,就发现了那句很重要的话

You may assume that there will be at most one factor more than 1000000.

这说明最大的因子(素数)并不会超过10^6次方

posted @   Gifur  阅读(532)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
TOP
点击右上角即可分享
微信分享提示