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

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
32 {
33  unsigned long sum = 1;
34  char ret = 0;
35 
36  for (unsigned long i = 2; i * i <= N; i++)
37  {
38  if (N % i == 0)
39  {
40  sum += i;
41  unsigned long tmp = N / i;
42  if (tmp != i)
43  {
44  sum += tmp;
45  }
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
88 {
89  /* optimized logic:
90  * i + j = N where both i and j should be abundant
91  * hence we can simply check for j = N - i as we loop through i
92  */
93  for (unsigned long i = get_next_abundant(1); i <= (N >> 1);
94  i = get_next_abundant(i))
95  {
96  if (is_abundant(N - i))
97  {
98 #ifdef DEBUG
99  printf("\t%4lu + %4lu = %4lu\n", i, N - i, N);
100 #endif
101  return 1;
102  }
103  }
104  return 0;
105 }
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

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