Little Difference

Little Difference

時間限制: 3 Sec  內存限制: 512 MB

題目描述

Little Lidia likes playing with numbers. Today she has a positive integer n, and she wants to decompose it to the product of positive integers.
Because Lidia is little, she likes to play with numbers with little difference. So, all numbers in decomposition should differ by at most one. And of course, the product of all numbers in the decomposition must be equal to n. She considers two decompositions the same if and only if they have the same number of integers and there is a permutation that transforms the first one to the second one.
Write a program that finds all decompositions, which little Lidia can play with today.

輸入

The only line of the input contains a single integer n (1≤n≤1018).

輸出

output the number of decompositions of n, or -1 if this number is infinite.

樣例輸入

12

樣例輸出

3


題目大意:給定一個正整數n,如果k1個a和k2個(a+1)相乘正好等於n,則爲一個解,輸出解的個數,如果有無數個解則輸出-1。


一個非常low的解法:如果暴力求解sqrt(1e18)的範圍肯定會超時。但如果k1+k2==n的話,則a一定等於(int)sqrt(n),將這種情況特判掉,則(k1+k2)>=3,所以a不會超過三次根號下1e18,這時候暴力一波也不會超時了。特殊情況:如果n是2的次冪,則n可以寫成k個2與無數個1的乘積,故有無數多個解。(注意:n本身也是一個解)


#include <bits/stdc++.h>
int main()
{
    long long n, m, i, ans, flag, j;
    ans = flag = j = 1;
    scanf("%lld", &n);
    for (i = 0; i <= 64; i++)
    {
        if (j == n)
        {
            flag=0;
            break;
        }
        j *= 2;
    }           //判斷n是不是2的次冪
    if (!flag)
        puts("-1");
    else
    {
        long long tmp = (long long) sqrt(n);
        if (tmp * tmp == n || tmp * tmp + tmp == n)
            ans++;          //特判(k1+k2==2)的情況
        m = std::min((long long) pow(n, 1.0 / 3) + 1, tmp - 1);         //確定暴力的範圍
        for (i = 2; i <= m; i++)
        {
            long long k = n;
            while (k % i == 0)
                k /= i;
            if (k == n)
                continue;       //如果(i+1)的k次方等於n,則下次循環i+1後會重複計數,故需防止重複計數
            while (k % (i + 1) == 0)
                k /= (i + 1);
            if (k == 1)
                ans++;
        }
        printf("%lld\n", ans);
    }
    return 0;
}

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