Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Number of Divisors

Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

Print how many positive integers divide n exactly.

Input

A single integer n.

Output

The number of divisors of n.

Constraints

Divisors come in pairs (i, n / i) with i ≤ √n, so a loop up to √n is enough. Count i once when i × i = n.

Example 1

Input

12

Output

6

Example 2

Input

1

Output

1

Hints

  1. If i divides n, so does n / i.
  2. One of i and n / i is always ≤ √n.

Approach

Loop i from 1 while i × i ≤ n. Each i that divides n gives two divisors, i and n / i — except when i × i = n, where they are the same number and count once. √(10^12) = 10^6 iterations, which is fast.

Complexity: O(√n) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    long long n;
    cin >> n;
    long long count = 0;
    for (long long i = 1; i * i <= n; i++)
        if (n % i == 0) count += (i * i == n) ? 1 : 2;
    cout << count << "\n";
    return 0;
}

Python solution

n = int(input())
count = 0
i = 1
while i * i <= n:
    if n % i == 0:
        count += 1 if i * i == n else 2
    i += 1
print(count)

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        long count = 0;
        for (long i = 1; i * i <= n; i++)
            if (n % i == 0) count += (i * i == n) ? 1 : 2;
        System.out.println(count);
    }
}

Solve Number of Divisors online · All practice problems