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

Problem 23 solution - optimization using look-up array More...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Include dependency graph for sol2.c:

Functions

char get_perfect_number (unsigned long N)
 
char is_abundant (unsigned long N)
 Is the given number an abundant number (1) or not (0)
 
unsigned long get_next_abundant (unsigned long N)
 Find the next abundant number after N and not including N.
 
char is_sum_of_abundant (unsigned long N)
 check if a given number can be represented as a sum of two abundant numbers. More...
 
int main (int argc, char **argv)
 Main function.
 

Variables

long MAX_N = 28123
 Limit of numbers to check.
 
char * abundant_flags = NULL
 This is the global array to be used to store a flag to identify if a particular number is abundant (1) or not (0). More...
 

Detailed Description

Problem 23 solution - optimization using look-up array

Author
Krishna Vedala

Optimization applied - compute & store abundant numbers once into a look-up array.

Function Documentation

◆ get_perfect_number()

char get_perfect_number ( unsigned long  N)
Returns
-1 if N is deficient
1 if N is abundant
0 if N is perfect
34 {
35  unsigned long sum = 1;
36  char ret = 0;
37 
38  for (unsigned long i = 2; i * i <= N; i++)
39  {
40  if (N % i == 0)
41  {
42  sum += i;
43  unsigned long tmp = N / i;
44  if (tmp != i)
45  sum += tmp;
46  }
47  }
48 
49  ret = sum == N ? 0 : (sum > N ? 1 : -1);
50 #ifdef DEBUG
51  printf("%5lu: %5lu : %d\n", N, sum, ret);
52 #endif
53  return ret;
54 }

◆ is_sum_of_abundant()

char is_sum_of_abundant ( unsigned long  N)

check if a given number can be represented as a sum of two abundant numbers.

Returns
1 - if yes
0 - if not
86 {
87  /* optimized logic:
88  * i + j = N where both i and j should be abundant
89  * hence we can simply check for j = N - i as we loop through i
90  */
91  for (unsigned long i = get_next_abundant(1); i <= (N >> 1);
92  i = get_next_abundant(i))
93  if (is_abundant(N - i))
94  {
95 #ifdef DEBUG
96  printf("\t%4lu + %4lu = %4lu\n", i, N - i, N);
97 #endif
98  return 1;
99  }
100  return 0;
101 }
Here is the call graph for this function:

Variable Documentation

◆ abundant_flags

char* abundant_flags = NULL

This is the global array to be used to store a flag to identify if a particular number is abundant (1) or not (0).

Using a whole byte to store a binary info would be redundant. We will use each byte to represent 8 numbers by relying on bits. This saves memory required by 1/8

N
#define N
number of digits of the large number
Definition: sol1.c:109
get_next_abundant
unsigned long get_next_abundant(unsigned long N)
Find the next abundant number after N and not including N.
Definition: sol2.c:70
is_abundant
char is_abundant(unsigned long N)
Is the given number an abundant number (1) or not (0)
Definition: sol2.c:59