Number of Divisors Using Prime Factorization
Abrar Eyasir
1 min read
Question: Given a positive integer n, we must find the total number of divisors for n.
Let d( n ) be the number of divisors for the natural number, n. We begin by writing the number as a product of prime factors: n = p^a* q^b* r ^c … then the number of divisors, d( n ) = ( a +1)( b +1)( c +1)…
int NOD ( ll n )
{
int nod = 1;
for ( auto p : primes ) {
if ( 1LL * p * p > n ) break;
if ( n % p == 0 ) {
int cnt = 0;
while ( n % p == 0 ) {
n /= p;
cnt++;
}
cnt++;
nod *= cnt;
}
}
if ( n > 1 ) {
nod *= 2;
}
return nod;
}
Mathematical Proof: How many divisors does a number have?)...
If the limits are not big, then You can use this code:
int nod[1123];
int lim = 1e3;
for ( int i = 1; i <= lim; i++ ) {
for ( int j = i; j <= lim; j += i ) {
nod[j]++;
}
}
Practice Questions:
583 - Prime Factors
11466 - Largest Prime Divisor
SPOJ.com - Problem MAIN12B
1
Subscribe to my newsletter
Read articles from Abrar Eyasir directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by