Remoteland

Remoteland(標題爲轉載鏈接)



Problem Description
In the Republic of Remoteland, the people celebrate their independence day every year. However, as it was a long long time ago, nobody can remember when it was exactly. The only thing people can remember is that today, the number of days elapsed since their independence (D) is a perfect square, and moreover it is the largest possible such number one can form as a product of distinct numbers less than or equal to n.
As the years in Remoteland have 1,000,000,007 days, their citizens just need D modulo 1,000,000,007. Note that they are interested in the largest D, not in the largest D modulo 1,000,000,007.
 

Input
Every test case is described by a single line with an integer n, (1<=n<=10,000, 000). The input ends with a line containing 0.
 

Output
For each test case, output the number of days ago the Republic became independent, modulo 1,000,000,007, one per line.
 

Sample Input
4 9348095 6297540 0
 

Sample Output
4 177582252 644064736
 

Source
 
#include <iostream>
#include <cstdio>
using namespace std;
int const maxSize=10000000;
long long ans[10000005];
int isPrime[10000005];
int primes[maxSize],l;

void init()//用於求出在範圍之內的所有的素數,順便將範圍內的所有的合數相乘得到ans[i],ans[i]表示不小於i的所有的合數的乘積,並求模
{
    ans[0] = ans[1] = 1;
    l = 0;
    for (int i=2; i<=maxSize; i++)
    {
        ans[i] = ans[i-1];//繼承i-1的ans
        if (!isPrime[i])
        {
            primes[l++] = i;//記錄(範圍內)所有的素數
            if (i < 3163)
                for (int j=i*i; j<=maxSize; j+=i)//標記合數,合數爲true
                    isPrime[j] = true;
        }
        else
            ans[i] = (ans[i] * i) % 1000000007;//求ans[i]
    }
}
int main()
{
    init();
    int n;
    while(~scanf("%d", &n)&& n)
    {
        long long num = ans[n];
        for (int i=0; i<l && primes[i] <= n/2; ++i)//n/2是因爲n以內的素數範圍不會大於n/2,更準確地說是n的算術平方根
        {
            int cnt = 0;
            int tn = n;
            while(tn >= primes[i])//這裏很巧妙的求出了某一個素數在基本算數定理中的冪
            {
                tn /= primes[i];
                cnt += tn;
            }
            if (cnt % 2 == 0)//由代碼上面的解釋而來
                num = (num * primes[i]) % 1000000007;
        }
        printf("%lld\n", num);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章