ACM 數論 質因數分解


Description

Tomorrow is contest day, Are you all ready? 
We have been training for 45 days, and all guys must be tired.But , you are so lucky comparing with many excellent boys who have no chance to attend the Province-Final. 

Now, your task is relaxing yourself and making the last practice. I guess that at least there are 2 problems which are easier than this problem. 
what does this problem describe? 
Give you a positive integer, please split it to some prime numbers, and you can got it through sample input and sample output. 
 

Input

Input file contains multiple test case, each case consists of a positive integer n(1<n<65536), one per line. a negative terminates the input, and it should not to be processed.
 

Output

For each test case you should output its factor as sample output (prime factor must come forth ascending ), there is a blank line between outputs.
 

Sample Input

60
12
-1
 

Sample Output

Case 1. 2 2 3 1 5 1
Case 2. 2 2 3 1

Hint

 60=2^2*3^1*5^1 
解題思路:
題目大意是給定一個數,讓我們將這個數進行因式分解,然后分別輸出它的質因子后面緊跟着的是這個質因子的個數,同時要求它的質因子是按從小到大的順序輸出的。格式要求,每一組測試案例之間要輸出一個空行,數據輸出時要求每輸出一個數字就要給一個空格(注意最后一個數字輸出時也要給出一個空格)。我覺得這個題目重點是讓我們判斷素數和累加每一個質因子的個數(我們用一個a數組來累加不同的質因子的個數,其中這個數組中元素的在下標就是這個質因子,每一個元素的值就是這個質因子的個數,記住對於每一組案例我們都要將a數組重新清0).
程序代碼:
#include <iostream>
#include <cstring>
using namespace std;
int a[65540];
int fun(int c)//判斷是不是素數,是就返回1,不是就返回0
{
    if(c==2)
        return 1;
    for(int i=2;i*i<=c;i++)
    {
        if(c%i==0)
        {
            return 0;
            break;
        }
    }
    return 1;
}
int main()
{
    int x,f=1;
    while(~scanf("%d", &x) && x > 0)
    {
        if(f!=1)//兩個案例之間要輸出一個空行
            cout<<endl;
        memset(a,0,sizeof(a));
        int i;
        int n=x;
        for(i=2;i<=x;i++)
        {
            if(fun(n))//如果素數了的情況
            {
                a[n]++;
                break;
            }
            if(fun(i)&&n%i==0)//要求是質因子
            {
                n=n/i;
                a[i]++;//累加質因子個數
                i=1;//由於i要++,所以從1開始,而且我們要求的是升序
            }
        }
        cout<<"Case "<<f++<<"."<<endl;
        for(int j=2;j<65540;j++)
            if(a[j])
                cout<<j<<" "<<a[j]<<" ";//輸出最后一個數據時,還是要輸出空格
        cout<<endl;
    }
    return 0;
}

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM