If is odd, then f(n) = n.
If is even, then f(n) = f(n / 2).
Let
Consider the partition of the set of positive integers from to into two subsets:
ODD — the set of odd numbers,
EVEN — the set of even numbers.
Among the positive integers from to , there are exactly
k = \left\lfloor (n + 1) / 2 \right\rfloor odd numbers;
l = \left\lfloor n / 2 \right\rfloor even numbers
Then:
At the same time:
To terminate the recursion, let g(0) = 0. Thus:
Example
Consider the first test case where n = 7.
Among the positive integers from to there are exactly:
k = \left\lfloor (7 + 1) / 2 \right\rfloor = 4 odd numbers;
l = \left\lfloor 7 / 2 \right\rfloor = 3 even numbers.
Algorithm implementation
Implement the function g.
long long g(long long n)
{
long long k = (n + 1) / 2;
if (n == 0) return 0;
return k * k + g(n / 2);
}The main part of the program. For each test case read the input value of and print .
while(scanf("%lld",&n) == 1)
printf("%lld\n",g(n));Java implementation
import java.util.*;
public class Main
{
static long g(long n)
{
long k = (n + 1) / 2;
if (n == 0) return 0;
return k * k + g(n / 2);
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
while(con.hasNext())
{
long n = con.nextLong();
System.out.println(g(n));
}
}
}Python implementation
Implement the function g.
def g(n):
if n == 0:
return 0
k = (n + 1) // 2
return k * k + g(n // 2)The main part of the program. For each test case read the input value of and print .
for line in sys.stdin:
n = int(line)
print(g(n))