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

Problem 25 solution implemented using arbitrarily large numbers represented as arrays More...

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

Macros

#define MAX_DIGITS   1000
 maximum number of digits
 

Functions

unsigned int add_numbers (unsigned char *a, unsigned char *b, unsigned char *c, int N)
 Function to add arbitraty length decimal integers stored in an array. More...
 
int print_number (unsigned char *number, int N)
 Print a large number.
 
unsigned int get_digits (unsigned char *number)
 Get number of digits in a large number.
 
int main (int argc, char *argv[])
 Main function.
 

Detailed Description

Problem 25 solution implemented using arbitrarily large numbers represented as arrays

Author
Krishna Vedala

Function Documentation

◆ add_numbers()

unsigned int add_numbers ( unsigned char *  a,
unsigned char *  b,
unsigned char *  c,
int  N 
)

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


a + b = c = new b

21 {
22  unsigned char carry = 0;
23  unsigned int i;
24 
25  for (i = 0; i < N; i++)
26  {
27  // printf("\t%d + %d + %d ", a[i], b[i], carry);
28  c[i] = carry + a[i] + b[i];
29  if (c[i] > 9) /* check for carry */
30  {
31  carry = 1;
32  c[i] -= 10;
33  }
34  else
35  {
36  carry = 0;
37  }
38  // printf("= %d, %d\n", carry, c[i]);
39  }
40 
41  while (carry != 0)
42  {
43  // printf("\t\t...adding new digit\n");
44  // printf("\t0 + %d + %d ", b[i], carry);
45  c[i] = carry + c[i];
46  if (c[i] > 9)
47  {
48  carry = 1;
49  c[i] -= 10;
50  }
51  else
52  {
53  carry = 0;
54  }
55  // printf("= %d, %d\n", carry, c[i]);
56  i++;
57  }
58  return i;
59 }