fork download
  1. // A Better (than Naive) Solution to find all divisors
  2. #include <iostream>
  3. #include <math.h>
  4. using namespace std;
  5.  
  6. // Function to print the divisors
  7. void printDivisors(int n)
  8. {
  9. // Note that this loop runs till square root
  10. for (int i=1; i<=sqrt(n); i++)
  11. {
  12. if (n%i == 0)
  13. {
  14. // If divisors are equal, print only one
  15. if (n/i == i)
  16. cout <<" "<< i;
  17.  
  18. else // Otherwise print both
  19. cout << " "<< i << " " << n/i;
  20. }
  21. }
  22. }
  23.  
  24. /* Driver program to test above function */
  25. int main()
  26. {
  27. cout <<"The divisors of 100 are: \n";
  28. printDivisors(100);
  29. return 0;
  30. }
  31.  
  32. // this code is contributed by shivanisinghss2110
  33.  
Success #stdin #stdout 0.01s 5500KB
stdin
Standard input is empty
stdout
The divisors of 100 are: 
 1 100 2 50 4 25 5 20 10