UVa 11526 H (n) (number theory)

Source: Internet
Author: User

11526-h (N)

Time limit:5.000 seconds

Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem &problem=2521

What is the value of this simple C + + function would return?

Long long H (int n) {

Long long res = 0;

for (int i = 1; I <= n; i=i+1) {

Res = (res + n/i);

}

return res;

}

Input
The the "a" of input is a integer t (T <= 1000) that indicates the number of test cases. Each of the next T-line would contain a single signed bit integer n.

Output
For the each test case, output would be a single line containing H (n).

Sample input Output for sample input

2
5
10
10
27

How do I calculate sum{[n/i]}? (1<=i<=n) (n<=2147483647)

n too big, hard to calculate certainly not, we first observe an example, see whether can draw some conclusions.

When n=20, the and type expands to

20+10+6+5+4+3+2+2+2+2+1+1+1+1+1+1+1+1+1+1

Note that the same number of the following is too many, may wish to simplify the following:

20+10+6+5+1* (20-10) +2* (10-6) +3* (6-5) +4* (5-4)

= (20+10+6+5) + (20+10+6+5) -4*4

=2 (20+10+6+5) -4*4

Maybe, we can

This article URL address: http://www.bianceng.cn/Programming/sjjg/201410/45351.htm

Thus, the complexity is reduced from O (n) to O (√n).

Complete code:

/*0.206s*/
    
#include <cstdio>  
#include <cmath>  
typedef long Long ll;  
    
inline ll ans (ll N)  
{  
    ll r = 0, m = sqrt (n), I;  
    for (i = 1; I <= m; ++i) R + = n/i;  
    Return (r << 1)-M * m;  
}  
    
int main ()  
{  
    int t;  
    ll N;  
    scanf ("%d", &t);  
    while (t--)  
    {  
        scanf ("%lld", &n);  
        printf ("%lld\n", ans (n));  
    }  
    return 0;  
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.