Total number of divisors for a given number using prime Factorization
#include <bits/stdc++.h>
using namespace std;
int divCount(int n)
{
bool mark[n+1];
memset(mark, true, sizeof(mark));
for(int i=2; i*i<=n; i++)
{
if(mark[i]==true)
{
for(int j=i*2; j<n; j+=i)
{
mark[j]=false;
}
}
}
int total=1;
for(int i=2; i<=n; i++)
{
if(mark[i])
{
int cnt=0;
if(n%i==0)
{
while(n%i==0)
{
n/=i;
cnt++;
}
total=total*(cnt+1);
}
}
}
return total;
}
int main ()
{
int n;
cin >> n;
cout << divCount(n) << endl;
return 0;
}
another example:
//this is my work__ finding number of divisor
#include <bits/stdc++.h>
using namespace std;
bool isprime(int x)
{
for(int i=2; i*i<=x; i++)
{
if(x%i==0){
return false;
}
}
return false;
}
int divcount(int n)
{
int total=1;
for(int i=2; i<=n; i++)
{
if(isprime(i)==false)
{
int cnt=0;
if(n%i==0)
{
while(n%i==0)
{
n/=i;
cnt++;
}
total=total*(cnt+1);
}
}
}
return total;
}
int main ()
{
int n;
cin >> n;
cout << divcount(n) << endl;
return 0;
}
Comments
Post a Comment