1. 程式人生 > >LightOJ-1336-Sigma Function (算術基本定理)

LightOJ-1336-Sigma Function (算術基本定理)

原題連結:
Sigma function is an interesting function in Number Theory. It is denoted by the Greek letter Sigma (σ). This function actually denotes the sum of all divisors of a number. For example σ(24) = 1+2+3+4+6+8+12+24=60. Sigma of small numbers is easy to find but for large numbers it is very difficult to find in a straight forward way. But mathematicians have discovered a formula to find sigma. If the prime power decomposition of an integer is
在這裡插入圖片描述


Then we can write
在這裡插入圖片描述
For some n the value of σ(n) is odd and for others it is even. Given a value n, you will have to find how many integers from 1 to n have even value of σ.

Input
Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 1012).

Output
For each case, print the case number and the result.

Sample Input
4

3

10

100

1000

Sample Output
Case 1: 1

Case 2: 5

Case 3: 83

Case 4: 947
題意:
輸入n,找出1~n之間的所有的σ(x)為偶數的個數。
題解:
根據偶*偶=偶,偶*奇=偶,奇*奇=奇,肯定是算奇數簡單,所以算出所有的奇數,最終n-奇數個數就是偶數的個數。根據σ函式得出,必需要函式每一項都要是奇數。
如果px==2,則px^(ex+1)-1必定為奇數;
如果px!=2,則px一定為奇數,由於函式是由等比數列求和得到的(1,px^1,px^2,…px^ex),由於奇數*奇數=奇數,所以此項共有ex+1個奇數相加,所以當ex為偶數時,此項為奇數。
以上就是兩種為奇數的可能性:1.px為2 或者2.ex為偶數
由於ex為偶數,所以一定可以化簡為某個數的平方,所以只要找出n以內的平方數就能夠找出所有的滿足第二個條件的個數,再加上第一個函式,有一個質因子是2,所以在平方數乘以二倍即可即2x^2.
為什麼只用乘以一次2,而不是2的i此方呢?
因為如果i為偶數,那麼可以換成某個數的平方,與第一個重複,如果是奇數都可以化成2

x^2的格式。
綜上所述:
只要找出所有的x^2和,2*x^2的個數就找出了所有的奇數可能。
附上AC程式碼:

#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
typedef long long LL;
int main()
{
    int t;
    scanf("%d",&t);
    for(int cas=1;cas<=t;cas++)
    {
        LL n,a,b;
        scanf("%lld",&n);
        a=sqrt(n);
        b=sqrt(n/2);
        printf("Case %d: %lld\n",cas,n-a-b);
    }
    return 0;
}

歡迎評論!