|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +void build_population_count_table(int *population_count_table, int size_of_table) |
| 5 | +{ |
| 6 | + int i; |
| 7 | + |
| 8 | + *(population_count_table + 0) = 0; |
| 9 | + *(population_count_table + 1) = 1; |
| 10 | + |
| 11 | + for(i = 2; i <= size_of_table; i++) |
| 12 | + { |
| 13 | + //f(2x) = f(x) because the binary string of x is just right shifted with a 0 appended |
| 14 | + //f(2x + 1) = f(x) + 1, the binary string of x is right shifted with a 1 appended |
| 15 | + //Writing this in one equation, as f(n) = f(n/2) + (n mod 2) |
| 16 | + *(population_count_table + i) = *(population_count_table + i/2) + (i % 2); |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +void display(int *population_count_table, int size_of_table) |
| 21 | +{ |
| 22 | + int i; |
| 23 | + for(i = 1; i <= size_of_table; i++) |
| 24 | + { |
| 25 | + printf("%d\t%d\n",i,*(population_count_table + i)); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +int main() |
| 30 | +{ |
| 31 | + int size_of_table; |
| 32 | + printf("Till what number do you want do you want to see the population count table ?\n"); |
| 33 | + scanf("%d", &size_of_table); |
| 34 | + |
| 35 | + int *population_count_table = malloc((size_of_table + 1)*sizeof(int)); |
| 36 | + build_population_count_table(population_count_table, size_of_table); |
| 37 | + |
| 38 | + display(population_count_table, size_of_table); |
| 39 | + free(population_count_table); |
| 40 | + return 0; |
| 41 | +} |
| 42 | + |
0 commit comments