Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
sol1.c File Reference

Problem 16 solution More...

#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
Include dependency graph for sol1.c:

Functions

int main (int argc, char **argv)
 Main function.
 

Detailed Description

Problem 16 solution

Author
Krishna Vedala

Function Documentation

◆ main()

int main ( int  argc,
char **  argv 
)

Main function.

13{
14 const double tmp = log(10) / log(2); /* required to get number of digits */
15 unsigned long MAX_NUM_DIGITS;
16 uint8_t *digits =
17 NULL; /* array to store individual digits. index 0 = units place */
18 int N = 1000, sum = 0;
19
20 if (argc == 2)
21 N = atoi(argv[1]);
22
23 MAX_NUM_DIGITS = (N + tmp) / tmp;
24
25 digits = calloc(MAX_NUM_DIGITS, sizeof(uint8_t));
26 digits[0] = 1;
27
28 if (!digits)
29 {
30 perror("Unable to allocate memory!");
31 return -1;
32 }
33
34 for (int i = 0; i < N; i++)
35 {
36 int carry = 0;
37 for (int j = 0; j < MAX_NUM_DIGITS; j++)
38 {
39 digits[j] = (digits[j] << 1) + carry; /* digit * 2 + carry */
40 // printf("\t value: %d\t", digits[j]);
41 if (digits[j] > 9)
42 {
43 carry = 1;
44 digits[j] -= 10;
45 }
46 else
47 carry = 0;
48 // printf("carry: %d\t value: %d\n", carry, digits[j]);
49
50 /* accumulate sum for last multiplication */
51 if (i == N - 1)
52 sum += digits[j];
53 }
54 }
55
56 printf("2^%d = ", N);
57 for (int i = MAX_NUM_DIGITS - 1; i >= 0; i--) putchar(digits[i] + 0x30);
58 printf("\n\t Sum: %d\t Num. digits: %lu\n", sum, MAX_NUM_DIGITS);
59
60 free(digits);
61 return 0;
62}
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
#define calloc(elemCount, elemSize)
This macro replace the standard calloc function with calloc_dbg.
Definition malloc_dbg.h:22