What's the Big O time complexity of this code? - c

#include <stdio.h>
int F(int L[], int p, int q) {
if (p < q) {
int r, f1, f2;
r = (p + q) / 2;
f1 = 2 * F(L, p, r);
f2 = 2 * F(L, r + 1, q);
return f1 + f2;
} else if (p == q) {
return L[p] * L[p];
}else{
return 0;
}
}
int main(void) {
int arr[8] = {1,2,3,4,5,6,7};
printf("%d", F(arr, 0, 7));
}
Someone said the time complexity of this code is O(n).
I don't understand it at all...
Isn't it O(logN) ???

Answer: The Big-O complexity is O(N)
Explanation:
The program takes a range of some size (i.e. q - p + 1) and cut that range into 2 half. Then it calls the function recursively on these two half ranges.
That process continues until the range has size 1 (i.e. p == q). Then there is no more recursion.
Example: Consider a start range with size 8 (e.g. p=0, q=7) then you will get
1 call with range size 8
2 calls with range size 4
4 calls with range size 2
8 calls with range size 1
So 7 calls (i.e. 1+2+4) with range size greater than 1 and 8 calls with range size equal to 1. A total of 15 calls which is nearly 2 times the starting range size.
So for a range size being a power of 2, you can generalize to be
Number of calls with range size greater than 1:
1+2+4+8+16+...+ rangesize/2 = rangesize - 1
Number of calls with range size equal to 1:
rangesize
So there will be exactly 2 * rangesize - 1 function calls when range size is a power of 2.
That is Big-O complexity O(N).
Want to try it out?
#include <stdio.h>
unsigned total_calls = 0;
unsigned calls_with_range_size_greater_than_one = 0;
unsigned calls_with_range_size_equal_one = 0;
int F(int L[], int p, int q) {
++total_calls;
if (p < q) {
++calls_with_range_size_greater_than_one;
int r, f1, f2;
r = (p + q) / 2;
f1 = 2 * F(L, p, r);
f2 = 2 * F(L, r + 1, q);
return f1 + f2;
} else if (p == q) {
++calls_with_range_size_equal_one;
return L[p] * L[p];
}else{
return 0;
}
}
int arr[200] = {1,2,3,4,5,6,7};
int main(void) {
for (int i=3; i < 128; i = i + i + 1)
{
total_calls=0;
calls_with_range_size_greater_than_one=0;
calls_with_range_size_equal_one=0;
F(arr, 0, i);
printf("Start range size: %3d -> total_calls: %3u calls_with_range_size_greater_than_one: %3u calls_with_range_size_equal_one: %3u\n", i+1, total_calls, calls_with_range_size_greater_than_one, calls_with_range_size_equal_one);
}
return 0;
}
Output:
Start range size: 4 -> total_calls: 7 calls_with_range_size_greater_than_one: 3 calls_with_range_size_equal_one: 4
Start range size: 8 -> total_calls: 15 calls_with_range_size_greater_than_one: 7 calls_with_range_size_equal_one: 8
Start range size: 16 -> total_calls: 31 calls_with_range_size_greater_than_one: 15 calls_with_range_size_equal_one: 16
Start range size: 32 -> total_calls: 63 calls_with_range_size_greater_than_one: 31 calls_with_range_size_equal_one: 32
Start range size: 64 -> total_calls: 127 calls_with_range_size_greater_than_one: 63 calls_with_range_size_equal_one: 64
Start range size: 128 -> total_calls: 255 calls_with_range_size_greater_than_one: 127 calls_with_range_size_equal_one: 128

Related

What is the limit to output numbers in C?

I was practicing programming in C, and when I ran this code, it came to a point where the outputting numbers just gave up lol, it was around the 30th number of the sequence.
What is the limit to output numbers in C?
(I was trying the Fibonacci sequence)
int main() {
int fibo, i, n, a, aux;
printf("Enter a number: ");
scanf("%d", &fibo);
n = 1; a = 1;
printf("1 1 ");
for(i = 3; i <= fibo; i++){
/* aux = n;
n = n + a;
a = aux;*/
n += a;
a = n - a;
printf("%d ", n);
}
}
What is the limit to output numbers in C?
There is no such limit. You can create a library to do arithmetic operations on arbitrary large numbers - and output them.
The question should probably be "what ranges can the fundamental types in C represent?" - and there are different limits for the different fundamental types.
Here's an incomplete list of some types taken from limits.h:
INT_MIN - minimum value of int
INT_MAX - maximum value of int
LLONG_MIN - minimum value of long long int
LLONG_MAX - maximum value of long long int
And from float.h:
DBL_MIN - minimum, normalized, positive value of double (typically 0.)
-DBL_MAX - lowest finite value representable by double
DBL_MAX - maximum finite value of duuble
Note that
an int is required to be at least 16 bit wide, but is often 32.
a long int is required to be at least 32 bit wide and often is.
a long long int is required to be at least 64 bites wide.
Depending on the type's bit width and how the implementation make use of these bits (two's complement, ones' complement, sign–magnitude and for floating points, if they use IEEE 754 or something else) affects the ranges they can represent.
Fibonacci numbers get very large very quickly, and will exceed the range of native integer types for relatively small n. On my system, the largest Fibonacci number I can compute with the following code using a regular signed int is F(44):
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
int main( int argc, char **argv )
{
if ( argc < 2 )
{
fprintf( stderr, "USAGE: %s n\n", argv[0] );
exit( 0 );
}
int n = strtol( argv[1], NULL, 10 );
int f[3] = { 0, 1, 0 };
printf( "INT_MAX = %d\n", INT_MAX );
for ( int i = 1; i <= n && INT_MAX - f[2] > f[1] + f[0]; i++ )
{
f[2] = f[1] + f[0];
f[0] = f[1];
f[1] = f[2];
printf( "fib %3d = %10d\n", i, f[2] );
}
return 0;
}
Output:
$ ./fib 50
INT_MAX = 2147483647
fib 1 = 1
fib 2 = 2
fib 3 = 3
fib 4 = 5
fib 5 = 8
fib 6 = 13
fib 7 = 21
fib 8 = 34
fib 9 = 55
fib 10 = 89
fib 11 = 144
fib 12 = 233
fib 13 = 377
fib 14 = 610
fib 15 = 987
fib 16 = 1597
fib 17 = 2584
fib 18 = 4181
fib 19 = 6765
fib 20 = 10946
fib 21 = 17711
fib 22 = 28657
fib 23 = 46368
fib 24 = 75025
fib 25 = 121393
fib 26 = 196418
fib 27 = 317811
fib 28 = 514229
fib 29 = 832040
fib 30 = 1346269
fib 31 = 2178309
fib 32 = 3524578
fib 33 = 5702887
fib 34 = 9227465
fib 35 = 14930352
fib 36 = 24157817
fib 37 = 39088169
fib 38 = 63245986
fib 39 = 102334155
fib 40 = 165580141
fib 41 = 267914296
fib 42 = 433494437
fib 43 = 701408733
fib 44 = 1134903170
If I switch to unsigned int, I can compute up to F(45). If I use long, I can get up to F(90). But even if I use unsigned long long, I'll still exceed its range with relatively small n.
To compute Fibonacci sequences for arbitrarily large n, you'll need a third-party bignum library like GMP:
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <gmp.h>
int main( int argc, char **argv )
{
if ( argc < 2 )
{
fprintf( stderr, "USAGE: %s n\n", argv[0] );
exit( 0 );
}
int n = strtol( argv[1], NULL, 10 );
mpz_t f[3];
mpz_init_set_str( f[0], "1", 10 );
mpz_init_set_str( f[1], "1", 10 );
for ( int i = 1; i <= n; i++ )
{
mpz_add( f[2], f[1], f[0] );
mpz_set( f[0], f[1] );
mpz_set( f[1], f[2] );
gmp_printf( "fib %d = %Zd\n", i, f[2] );
}
return 0;
}
For n == 1000, I get
fib 1000 = 113796925398360272257523782552224175572745930353730513145086634176691092536145985470146129334641866902783673042322088625863396052888690096969577173696370562180400527049497109023054114771394568040040412172632376
Edit
Gah, the sequence starts off wrong - it should be 1, 1, 2, .... But my main point remains.

hackerrank solution in c for "Array Manipulation"

long arrayManipulation(int n, int queries_rows, int queries_columns, int** queries)
{
long num, a, b, maxnum = INT_MIN;
long* arrptr = calloc(n, sizeof(long));
for(int i = 0;i<(queries_rows);i++)
{
num = queries[i][2];
if(num==0)
{
continue;
}
printf("%ld ", num);
a = queries[i][0];
b = queries[i][1];
for(long i = a-1;i<b;i++)
{
arrptr[i] += num;
if(maxnum<(arrptr[i]))
{
maxnum = arrptr[i];
}
}
}
free(arrptr);
return maxnum;
}
I have to optimize this program so that it can be executed in less time can you help??
this program is supposed to initialize an array of a size n(function argument) with 0(lets call array arr)
then there will be query in form
a b k
1 2 3
4 5 6
and then in array arr we have add k between the limits a and b
and then return max of arr
example
Sample Input
5 3
1 2 100
2 5 100
3 4 100
Sample Output
200
Explanation
After the first update list will be 100 100 0 0 0.
After the second update list will be 100 200 100 100 100.
After the third update list will be 100 200 200 200 100.
The returned answer will be 200.
Actually you can think of a much better algorithm that will do the job in O(n) instead of doing the same thing in O(n*n) what you are doing.
So the algorithm looks like this
1-initialize the array with size n+1 with all the 0's in it
2-for every query L, R, X increase array[L] by the value of X and decrease the value of array[R+1] by X
3-last step would be to get the prefix sum of the array which will give you the final processed array where you can find the maximum and return as an answer.
For eg.
5 3
arr=[0,0,0,0,0,0]
step 1:
1 2 100
arr=[100 0 -100 0 0 0]
step 2:
2 5 100
arr=[100 100 -100 0 0 -100]
step 3:
3 4 100
arr=[100 100 0 0 -100 -100]
step 4:
prefix sum
arr=[100 200 200 200 100 0] -> That's your final array and then you can easily return maximum from this array
Hope this helps! tell me if you can't understand anything I will be happy to help
Since I have been working on it I found a good and understandable code on it with O(n) approach, it works well under required time and it doesn't have errors.
long arrayManipulation(int n, int queries_rows, int queries_columns, int** queries)
{
long num, a, b, maxnum = INT_MIN;
int* arrptr = calloc(n, sizeof(long));
for(int i=0;i<queries_rows;i++)
{
arrptr[queries[i][0] -1] +=queries[i][2];
arrptr[queries[i][1]] -= queries[i][2];
}
long count = 0;
for(int i=0;i<n;i++)
{
count += arrptr[i];
arrptr[i]=count;
if(count>maxnum) maxnum=count;
}
printf("%ld\n",maxnum);
free(arrptr);
return maxnum;
}

use of rand function to assign a value randomly [duplicate]

This question already has answers here:
How to create a random permutation of an array?
(3 answers)
Closed 6 years ago.
i am doing a homework. i put rand function in a loop.
int counter = 1;
while ( counter <= 10 ){
variable1 = rand() % 5 + 1;
printf("%d", variable);
counter = counter + 1;
In this code, rand function assigns different value to variable called variable1 but sometimes it assigns same value because range of rand function is narrow. how can i perform that rand function assign different number to variable at the time when loop returns every time.
While rand() is not the greatest random function it should do the trick for many jobs and certainly for most homework. It is perfectly valid to have the same number returned twice in a row from a random function -- as the function should not have any memory of what values were previously returned.
The best way to understand this, is with an example of a coin-toss. Every coin toss is random, and the coin has no memory of the previous toss, so it is possible to flip a coin 32 times in a row and they all comes up head -- if every coin toss is a bit in a 32 bit integer you have created the binary value of integer zero.
However human tend to think (intuition) that having the same value returned more than once is "wrong" for a random function -- but our intuition is wrong on this account.
If you for some reason do want to not repeat the number from one loop to the next, then you will need to program that regardless of which random functions you use -- since any random function would be capable of returning the same values twice.
So something like this would do it;
int counter = 1;
int prevValue = -1;
while ( counter <= 10 ){
do {
variable1 = rand();
} while (variable1 == prevValue);
prevValue = variable1;
variable1 = variable1 % 5 + 1;
printf("%d", variable);
counter = counter + 1;
}
Note that this is still capable of printing the same value twice, since 10 and 15 would be different values before the %5 but would be the same after. If you want the %5 to be taken into account, so the printf never print the same value twice in a row, you would need to move the %5 inside the loop.
In your code snippet i can't find which instruction is the last one inside while. If you want to get different numbers every program run you should use srand() function before while.
But as you mentioned before. Your range (1 - 5) is to narrow to get 10 unique values every time.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int counter = 1;
int variable1 = 0;
srand(time(NULL));
while ( counter <= 10 ) {
variable1 = rand() % 5 + 1;
printf("%d ", variable1);
counter = counter + 1;
}
putchar('\n');
return 0;
}
how can i perform that rand function assign different number to variable at the time when loop returns every time?
I take this to mean OP does not want to generate the same number twice in a row.
On subsequent iterations, use %(n-1)
int main(void) {
int counter;
int variable;
for (counter = 1; counter <= 10; counter++) {
// First time in loop
if (counter <= 1) {
variable = rand() % 5 + 1;
} else {
int previous = variable;
variable = rand() % (5 - 1) + 1;
if (variable >= previous) variable++;
}
printf("%d\n", variable);
}
return 0;
}
In order to generate a unique list of random numbers, you must check each number generated against the list of numbers previously generated to insure there is no duplicate. The easiest way is to store your previously generated numbers in an array to check against. Then you simply iterate over the values in the array, and if your most recent number is already there, create a new one.
For example, you can use a simple flag to check if your are done. e.g.
while (counter < MAXI){
int done = 0;
while (!done) { /* while done remains 0 (not done) */
done = 1;
tmp = rand() % MAXI + 1; /* generate radom number */
for (i = 0; i < counter; i++) /* check again previous */
if (tmp == array[i]) /* if num already exists */
done = 0; /* set as (not done) */
}
array[counter++] = tmp; /* assign random value */
}
Or you can use the old faithful goto to do the same thing:
while (counter < MAXI) {
gennum:
tmp = rand() % MAXI + 1;
for (i = 0; i < counter; i++)
if (tmp == array[i])
goto gennum;
array[counter++] = tmp;
}
Whichever makes more sense to you. Putting together a full example, you could do:
#include <stdio.h>
#include <stdlib.h> /* for rand */
#include <time.h> /* for time */
enum { MAXI = 10 };
int main (void) {
int array[MAXI] = {0}, counter = 0, i, tmp;
srand (time (NULL)); /* initialize the semi-random number generator */
while (counter < MAXI){
int done = 0;
while (!done) { /* while done remains 0 (not done) */
done = 1;
tmp = rand() % MAXI + 1; /* generate radom number */
for (i = 0; i < counter; i++) /* check again previous */
if (tmp == array[i]) /* if num already exists */
done = 0; /* set as (not done) */
}
array[counter++] = tmp; /* assign random value */
}
for (i = 0; i < MAXI; i++)
printf (" array[%2d] = %d\n", i, array[i]);
return 0;
}
(note: the number your mod (%) the generated number by must be equal to or greater than the number of values you intend to collect -- otherwise, you cannot generate a unique list.)
Example Use/Output
$ ./bin/randarray
array[ 0] = 8
array[ 1] = 2
array[ 2] = 7
array[ 3] = 9
array[ 4] = 1
array[ 5] = 4
array[ 6] = 3
array[ 7] = 10
array[ 8] = 6
array[ 9] = 5
A Shuffled Sequence
Given the discussion in the comments, a good point was raised concerning whether your goal was to create unique set of random numbers (above) or a random set from a sequence of numbers (e.g. any sequence, say 1-50 in shuffled order). In the event you are looking for the latter, then an efficient method to create the shuffled-sequence is using a modified Fisher-Yates shuffle knows as The "inside-out" algorithm.
The algorithm allows populating an uninitialized array with a shuffled sequence from any source of numbers (whether the source can be any manner of generating numbers). Essentially, the function will swap the values within an array at the current index with the value held at a randomly generated index. An implementation would look like:
/** fill an uninitialized array using inside-out fill */
void insideout_fill (int *a, int n)
{
int i, val;
for (i = 0; i < n; i++) {
val = i ? randhq (i) : 0;
if (val != i)
a[i] = a[val];
a[val] = i; /* i here can be any source, function, etc.. */
}
}
(where randhq is any function that generates a random value (0 <= val < n))
A short example program that uses the function above to generate a shuffled array of value from 0 - (n-1) is shown below. The example generates a shuffled sequence of values in array using the inside-out algorithm, and then confirms the sequence generation by sorting the array:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insideout_fill (int *a, int n);
int randhq (int max);
void prnarray (int *a, size_t n, size_t strd, int wdth);
int intcmp (const void *a, const void *b);
int main (int argc, char **argv) {
srand (time (NULL));
int arrsz = argc > 1 ? (int)strtol (argv[1], NULL, 10) : 50;
int array[arrsz];
insideout_fill (array, arrsz);
printf ("\n array initialized with inside-out fill:\n\n");
prnarray (array, arrsz, 10, 4);
qsort (array, arrsz, sizeof *array, intcmp);
printf ("\n value confirmation for inside-out fill:\n\n");
prnarray (array, arrsz, 10, 4);
return 0;
}
/** fill an uninitialized array using inside-out fill */
void insideout_fill (int *a, int n)
{
int i, val;
for (i = 0; i < n; i++) {
val = i ? randhq (i) : 0;
if (val != i)
a[i] = a[val];
a[val] = i; /* i here can be any source, function, etc.. */
}
}
/** high-quality random value in (0 <= val <= max) */
int randhq (int max)
{
unsigned int
/* max <= RAND_MAX < UINT_MAX, so this is okay. */
num_bins = (unsigned int) max + 1,
num_rand = (unsigned int) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
int x;
/* carefully written not to overflow */
while (num_rand - defect <= (unsigned int)(x = rand()));
/* truncated division is intentional */
return x/bin_size;
}
/** print array of size 'n' with stride 'strd' and field-width 'wdth' */
void prnarray (int *a, size_t n, size_t strd, int wdth)
{
if (!a) return;
register size_t i;
for (i = 0; i < n; i++) {
printf (" %*d", wdth, a[i]);
if (!((i + 1) % strd)) putchar ('\n');
}
}
/** qsort integer compare */
int intcmp (const void *a, const void *b)
{
return *((int *)a) - *((int *)b);
}
Example Use/Output
$ ./bin/array_io_fill
array initialized with inside-out fill:
40 15 35 17 27 28 20 14 32 39
31 25 29 45 4 16 13 9 49 7
11 23 8 33 48 37 41 34 19 38
24 26 47 44 5 0 6 21 43 10
2 1 18 22 46 30 12 42 3 36
value confirmation for inside-out fill:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
Look it over and let me know if you have any questions.

Need help for find the logic of a heuristic sequence

I'm developing a system that can explore entirely a simple heuristic map of this gender (which can have different numbers of branches, and different depths) :
Simple heuristic map
So, I'm saving the positions explored in an int array of the size of the depth of the map. The goal is to explore all nodes of the map, so to have this output : 0 2 6, 0 2 7, 0 3 8, 0 3 9, 1 4 10 etc.. But actually with my code (which needs to be called several times because it can update just one time the array), i have this : 0 2 6, 0 2 7, 0 3 8, **1** 3 9, 1 4 10 etc..
This is my code, I don't know how to solve this problem..
void get_next_branch(int *s, int nbr_branch, int size)
{
int a;
a = 0;
while (a < size)
{
condition = (size - a)/(nbr_branch - 1);
if (condition)
{
if (s[size - 1] % (condition) + 1 == condition)
s[a]++;
}
a++;
}
}
And this is the main example who call this function.
int main(void)
{
int id[3] = {0, 2, 6};
while (id[2] < 13)
{
printf("%d %d %d\n", id[0], id[1], id[2]);
get_next_branch(id, 2, 3);
}
return (0);
}
I thank you in advance!
You might want to use a closed formula for this problem
b being the number of branches
d the depth you want to find the numbers in (d >= 0)
we get immediately
Number of nodes at depth d = bd+1
(since at depth 0 we have already two nodes, there is no "root" node used).
The number of the first node at depth d is the sum of the number of nodes of the lower levels. Basically,
first node number at depth 0 = 0
first node number at depth d > 0 = b1 + b2 + b3 + ... + bd
This is the sum of a geometric series having a ratio of b. Thanks to the formula (Wolfram)
first node number at depth d = b * (1 - bd) / (1 - b)
E.g. with b == 2 and d == 2 (3rd level)
Number of nodes: 2 ^ 3 = 8
Starting at number: 2 * (1 - 2^2) / (1 - 2) = 6
A program to show the tree at any level can be done from the formulas above.
To print a number of levels of a tree with b branches:
Utility power function
int power(int n, int e) {
if (e < 1) return 1;
int p=n;
while (--e) p *= n;
return p;
}
The two formulas above
int nodes_at_depth(int branches, int depth) {
return power(branches, depth+1);
}
int first_at_depth(int branches, int depth) {
return (branches * (1 - power(branches, depth))) / (1 - branches);
}
Sample main program, to be called
./heuristic nb_of_branches nb_of_levels
that calls the two functions
int main(int argc, char **argv)
{
if (argc != 3) return 1;
int b = atoi(*++argv);
int d = atoi(*++argv);
if (b < 2) return 2;
int i,j;
for (i=0 ; i<d ; i++) {
int n = nodes_at_depth(b, i); // number of nodes at level i
int s = first_at_depth(b, i); // first number at that level
for (j=0 ; j<n ; j++) printf(" %d", s+j);
printf("\n");
}
return 0;
}
Calling
./heuristic 2 4
gives
0 1
2 3 4 5
6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

Optimize a summing of array (subset problem)

In the hottest part of my program (90% of time according to gprof), I need to sum one array A into another B. Both arrays are 2^n (n is 18..24) sized and holds an integer (for simplicity, actually the element stored is mpz_t or small int array). The rule of summing: for each i in 0..2^n-1, set B[i] = sum (A[j]), where j is bit vector, and j & ~ i == 0 (in other words, k-th bit of any j can't be set to 1 if k-th bit of i is not 1).
My current code (this is a body of innermost loop) does this in the time of 2^(1.5 * n) sums, because I will iterate for each i on (in average) 2^(n/2) elements of A.
int A[1<<n]; // have some data
int B[1<<n]; // empty
for (int i = 0; i < (1<<n); i++ ) {
/* Iterate over subsets */
for (int j = i; ; j=(j-1) & i ) {
B[i] += A[j]; /* it is an `sum`, actually it can be a mpz_add here */
if(j==0) break;
}
}
My I mentioned, that almost any sum is recomputed from the values, summed earlier. I suggest, there can be code, doing the same task in the time of n* 2^n sums.
My first idea is that B[i] = B[i_without_the_most_significant_bit] + A[j_new]; where j_new is only j's having the most_significant bit from i in '1' state. This halves my time, but this is not enough (still hours and days on real problem size):
int A[1<<n];
int B[1<<n];
B[0] = A[0]; // the i==0 will not work with my idea and clz()
for (int i = 1; i < (1<<n); i++ ) {
int msb_of_i = 1<< ((sizeof(int)*8)-__builtin_clz(i)-1);
int i_wo_msb = i & ~ msb;
B[i] = B[i_wo_msb];
/* Iterate over subsets */
for (int j_new = i; ; j_new=(j_new-1) & i ) {
B[i] += A[j_new];
if(j_new==msb) break; // stop, when we will try to unset msb
}
}
Can you suggest better algorithm?
Additional image, list of i and j summed for each i for n=4:
i j`s summed
0 0
1 0 1
2 0 2
3 0 1 2 3
4 0 4
5 0 1 4 5
6 0 2 4 6
7 0 1 2 3 4 5 6 7
8 0 8
9 0 1 8 9
a 0 2 8 a
b 0 1 2 3 8 9 a b
c 0 4 8 c
d 0 1 4 5 8 9 c d
e 0 2 4 6 8 a c e
f 0 1 2 3 4 5 6 7 8 9 a b c d e f
Note the similarity of figures
PS the msb magic is from here: Unset the most significant bit in a word (int32) [C]
Divide and conquer anyone? Now not in-place.
void sums(int *a, int n, int *b) {
if (n <= 0) {
*b = *a;
return;
}
int m = 1 << (n - 1);
sums(a, n - 1, b);
sums(a + m, n - 1, b + m);
for (int i = 0; i < m; i++) {
b[m + i] += b[i];
}
}

Resources