i need to find the all the divisors of a num(int) i am applying this approach
for(int i=1;i<=n/2;i++)}
if(n%i==0) v.push_back(i);
}
here vector v will return all the divisors of input number n
but this is quite slow method can anyone please suggest me a faster approach to do this job
thanks
Vectors have two sizes: size and capacity. Each push_back() increases the size by one and assigns the parameter to the tail of the vector. The capacity if the physical size of the array. If at the time of the push_back() the size is the same as the capacity, the vector has to create a larger array, copy the original to the new, and destroy the original. This is quite expensive. If you reserve an appropriate number of elements at the start, push_back() will only need to reallocate until the size reaches the capacity. If you reserve enough, push_back() never need to reallocate.
I was wrong. You should reserve sqrt(n)*2 and at each loop you should push_back() i and n/i. Note that this will result in an unsorted vector but it's the fastest method I can think of to find all divisors. It takes only O(n1/2) time.
The method should work to tell those apart. However, you shouldn't use it to find primes, since on average it takes more iterations to find all the divisors of a number than to check if the number is prime.
EDIT:
n=12
(int)sqrt(12)=3
12%1==0, so 1 and 12, because 12/1==12
12%2==0, so 2 and 6, because 12/2==6
12%3==0, so 3 and 4, because 12/3=4
Done.