C program to generate divisors of an integerLoops / By Neeraj Mishra #include<stdio.h> #include<conio.h> void main() { int i,n; clrscr(); //to clear the screen printf(“Enter any number:”); scanf(“%d”,&n); printf(“nDivisors of %d are”,n); for(i=1;i<n/2;++i) if(n%i==0) printf(” %d”,i); getch(); //to stop the screen }
Steven Wang March 18, 2014 at 2:34 am You're missing a divisor! If the number is even, you'll always miss n/2. Change the conditional toi <= n/2. Reply
abdelrhman hamdy metwaly February 5, 2018 at 12:47 pm This algorithm is O(n) complexity There is another method to calculate the divisors in O(sqrt(n)) complexity vector d; void genDivisors(int num){ d.clear(); int i=1; for(;i*i<num;i++) if(num%i==0) {d.push_back(i),d.push_back(num/i);} if(i*i==num)d.push_back(i); sort(d.begin(),d.end()); } Reply
You're missing a divisor! If the number is even, you'll always miss n/2. Change the conditional to
i <= n/2.
This algorithm is O(n) complexity
There is another method to calculate the divisors in O(sqrt(n)) complexity
vector d;
void genDivisors(int num){
d.clear();
int i=1;
for(;i*i<num;i++)
if(num%i==0) {d.push_back(i),d.push_back(num/i);}
if(i*i==num)d.push_back(i);
sort(d.begin(),d.end());
}
please sir explain this program