Advertisement
Guest User

Divisor script in C

a guest
May 20th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // C script for calculating the divisors of a number.
  4. // It turns out calculating the square root was not required -- we can determine if we hit it ourselves. Go to the 28th line to see how.
  5.  
  6. // I wrote this script because I wanted a script that is faster than the Python one.
  7. // Indeed, computing the divisors of 9007199254740992 was about 9x faster (23642ms on Python vs. 2641ms on C).
  8.  
  9. int main(int argc, char** argv) {
  10. if (argc < 2) { // For some reason, argc is 1 if no arguments are specified.
  11. puts("Specify the number whose divisors you want to take as the first argument.");
  12. return 1;
  13. }
  14. unsigned long long num = 0;
  15. // The below "for" loop converts a string into an unsigned long long.
  16. // Say you input "123".
  17. // The loop:
  18. // - takes the character "1" (value 49), subtracts 48, gets 1.
  19. // - multiplies the number by 10 and adds 1 (result = 1).
  20. // - takes the character "2" (value 50), subtracts 48, gets 2.
  21. // - multiplies the number by 10 and adds 2 (result = 12).
  22. // - takes the character "3" (value 51), subtracts 48, gets 3.
  23. // - multiplies the number by 10 and adds 3 (result = 123).
  24. for (int i = 0; argv[1][i]; ++i) {
  25. num = argv[1][i]-48+num*10;
  26. }
  27. // i is an unsigned long because the square root of an unsigned long long will always be an unsigned long.
  28. for (unsigned long i = 1; num/i>=i; // This is the part that stops at the square root of the number.
  29. // When evaluating a non-square number:
  30. // 23 / 1 = 23
  31. // 23 / 2 = 11.5
  32. // 23 / 3 = 7.(6)
  33. // 23 / 4 = 5.75
  34. // 23 / 5 = 4.6
  35. // When evaluating a square number:
  36. // 25 / 1 = 25
  37. // 25 / 2 = 12.5
  38. // 25 / 3 = 8.(3)
  39. // 25 / 4 = 6.25
  40. // 25 / 5 = 5
  41. // We stop once the result, rounded down, is less than or equal to the divisor (the opposite of it being greater than the divisor).
  42. // In both examples, the square root of the number, rounded down, is the result of the final division rounded down.
  43. ++i) {
  44. if (num % i == 0) {
  45. printf("%lu\n",i);
  46. if (i * i != num) { // To avoid getting a duplicate result.
  47. printf("%llu\n",num/i);
  48. }
  49. }
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement