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>
|
#define | MAX_DIGITS 1000 |
| maximum number of digits
|
|
|
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. More...
|
|
unsigned int | get_digits (unsigned char *number) |
| Get number of digits in a large number. More...
|
|
int | main (int argc, char *argv[]) |
| Main function. More...
|
|
Problem 25 solution implemented using arbitrarily large numbers represented as arrays
- Author
- Krishna Vedala
◆ 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
28 c[i] = carry + a[i] + b[i];
29 if (c[i] > 9)
30 {
31 carry = 1;
32 c[i] -= 10;
33 }
34 else
35 {
36 carry = 0;
37 }
38
39 }
40
41 while (carry != 0)
42 {
43
44
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
56 i++;
57 }
58 return i;
59}
◆ get_digits()
unsigned int get_digits |
( |
unsigned char * |
number | ) |
|
Get number of digits in a large number.
76{
78 while (number[digits] == 0) digits--;
79 return digits;
80}
#define MAX_DIGITS
maximum number of digits
Definition: sol1.c:13
◆ main()
int main |
( |
int |
argc, |
|
|
char * |
argv[] |
|
) |
| |
Main function.
84{
85 unsigned char
89
93
94 fn[0] = 1;
95 fn1[1] = 1;
96
97 unsigned int index = 1, digit_count = 1;
98
99 clock_t start_time = clock();
100 do
101 {
102 digit_count =
add_numbers(fn, fn1, sum, digit_count);
103
104
105
106
107
108
110 {
111 break;
112 }
115 index++;
117 clock_t end_time = clock();
118
119 printf("Time taken: %.4g ms\n",
120 1e3 * (end_time - start_time) / CLOCKS_PER_SEC);
121 printf(
"The nth term for %d digits: %u \n",
MAX_DIGITS, index--);
123
124 return 0;
125}
int print_number(uint8_t *number, uint8_t N, int8_t num_digits_to_print)
Function to print a long number.
Definition: sol1.c:92
int add_numbers(uint8_t *a, uint8_t *b, uint8_t N)
Function to add arbitrary length decimal integers stored in an array.
Definition: sol1.c:48
◆ print_number()
int print_number |
( |
unsigned char * |
number, |
|
|
int |
N |
|
) |
| |
Print a large number.
63{
64 int start_pos = N - 1;
65
66
67 while (number[start_pos] == 0) start_pos--;
68
69 for (int i = start_pos; i >= 0; i--) putchar(number[i] + 0x30);
70
71 return 0;
72}