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