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

Problem 12 solution More...

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

Functions

long count_divisors (long long n)
 
int main (int argc, char **argv)
 

Detailed Description

Problem 12 solution

Author
Krishna Vedala

Function Documentation

◆ count_divisors()

long count_divisors ( long long  n)

Get number of divisors of a given number

If \(x = a \times b\), then both \(a\) and \(b\) are divisors of \(x\). Since multiplication is commutative, we only need to search till a maximum of \(a=b = a^2\) i.e., till \(\sqrt{x}\). At every integer till then, there are eaxctly 2 divisors and at \(a=b\), there is only one divisor.

20 {
21  long num_divisors = 0;
22 
23  for (long long i = 1; i < sqrtl(n) + 1; i++)
24  if (n % i == 0)
25  num_divisors += 2;
26  else if (i * i == n)
27  num_divisors += 1;
28 
29  return num_divisors;
30 }

◆ main()

int main ( int  argc,
char **  argv 
)

Main function

34 {
35  int MAX_DIVISORS = 500;
36  long i = 1, num_divisors;
37  long long triangle_number = 1;
38 
39  if (argc == 2)
40  MAX_DIVISORS = atoi(argv[1]);
41 
42  while (1)
43  {
44  i++;
45  triangle_number += i;
46  num_divisors = count_divisors(triangle_number);
47  if (num_divisors > MAX_DIVISORS)
48  break;
49  }
50 
51  printf("First Triangle number with more than %d divisors: %lld\n",
52  MAX_DIVISORS, triangle_number);
53 
54  return 0;
55 }
Here is the call graph for this function:
count_divisors
long count_divisors(long long n)
Definition: sol1.c:19