Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
sol1.c File Reference

Problem 13 solution More...

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

Macros

#define N   10
 number of digits of the large number
 
#define N2   (N + 10)
 number of digits in output number
 

Functions

int get_number (FILE *fp, char *buffer, uint8_t *out_int)
 Function to read the number from a file and store it in array. More...
 
int add_numbers (uint8_t *a, uint8_t *b, uint8_t N)
 Function to add arbitraty length decimal integers stored in an array. More...
 
int print_number (uint8_t *number, uint8_t N, int8_t num_digits_to_print)
 Function to print a long number.
 
int main (void)
 Main function.
 

Detailed Description

Problem 13 solution

Author
Krishna Vedala

Function Documentation

◆ add_numbers()

int add_numbers ( uint8_t *  a,
uint8_t *  b,
uint8_t  N 
)

Function to add arbitraty length decimal integers stored in an array.

a + b = c = new b

45 {
46  int carry = 0;
47  uint8_t *c = b; /* accumulate the result in the array 'b' */
48 
49  for (int i = 0; i < N; i++)
50  {
51  // printf("\t%d + %d + %d ", a[i], b[i], carry);
52  c[i] = carry + a[i] + b[i];
53  if (c[i] > 9) /* check for carry */
54  {
55  carry = 1;
56  c[i] -= 10;
57  }
58  else
59  carry = 0;
60  // printf("= %d, %d\n", carry, c[i]);
61  }
62 
63  for (int i = N; i < N + 10; i++)
64  {
65  if (carry == 0)
66  break;
67  // printf("\t0 + %d + %d ", b[i], carry);
68  c[i] = carry + c[i];
69  if (c[i] > 9)
70  {
71  carry = 1;
72  c[i] -= 10;
73  }
74  else
75  carry = 0;
76  // printf("= %d, %d\n", carry, c[i]);
77  }
78  return 0;
79 }

◆ get_number()

int get_number ( FILE *  fp,
char *  buffer,
uint8_t *  out_int 
)

Function to read the number from a file and store it in array.


index 0 of output buffer => units place
index 1 of output buffer => tens place and so on i.e., index i => 10^i th place

17 {
18  long l = fscanf(fp, "%s\n", buffer);
19  if (!l)
20  {
21  perror("Error reading line.");
22  return -1;
23  }
24  // printf("Number: %s\t length: %ld, %ld\n", buffer, strlen(buffer), l);
25 
26  long L = strlen(buffer);
27 
28  for (int i = 0; i < L; i++)
29  if (buffer[i] < 0x30 || buffer[i] > 0x39)
30  {
31  perror("found inavlid character in the number!");
32  return -1;
33  }
34  else
35  out_int[L - i - 1] = buffer[i] - 0x30;
36 
37  return 0;
38 }
L
Definition: list.h:8
N
#define N
number of digits of the large number
Definition: sol1.c:109