NetEase 2017 School recruit Pen question the biggest odd approximate

Source: Internet
Author: User

Topic:

Defines the maximum odd number of x for a function f (x), and x is a positive integer, such as f (44) = 11.

Now give an N, need to ask out F (1) + F (2) + F (3) + ... + f (n)

Example: N = 7

F (1) + F (2) + F (3) + F (4) + F (5) + F (6) + f (7) = 1 + 1 + 3 + 1 + 5 + 7 = 21.

Analysis:

The largest approximate number of odd numbers is itself, and the maximum number of even numbers is the odd number after all the even factors are removed. So the intuitive idea is to walk through the add up.

Code:

1#include <iostream>2 using namespacestd;3 intMain () {4     Long LongN;5CIN >>N;6     Long Longresult =0;7      for(Long Longi =1; I <= N; ++i) {8         inttemp =i;9          while(Temp%2==0) {TenTemp/=2; One         } AResult + =temp; -     } -cout << Result <<Endl; the     return 0; -}

However, the value range of n is 10^10, so the O (n) algorithm is timed out.

Consider optimization, set sum (i) = f (1) + F (2) + ... + f (i);

In the process of seeking sum (i), so f (i), I is an odd number can be directly asked, that is I itself.

The problem is to ask for all f (i), I is an even number and.

Because it is the maximum odd approximate, so f (2k) = f (k), so f (2) + F (4) + ... + f (2k) = f (1) + F (2) + ... + f (k);

So

SUM (i) = SUM (I/2) + 1 + 3 + ... + i-1 (i is even)

= SUM (i-1) + I (I is odd)

Time complexity O (logn), can be solved.

1#include <iostream>2 using namespacestd;3 Long LongSumLong LongN) {4     if(n = =1) {5         return 1;6     }7     if(n%2==0) {8         returnSUM (N/2) + N * N/4;9     }Ten     Else { One         returnSUM (N-1) +N; A     } - } - intMain () { the     intN; -CIN >>N; -cout << sum (N) <<Endl; -}

NetEase 2017 School recruit Pen question the biggest odd approximate

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.