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)
 Get number of divisors of a given number. More...
 
int main (int argc, char **argv)
 Main function.
 

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 }