Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- // C script for calculating the divisors of a number.
- // 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.
- // I wrote this script because I wanted a script that is faster than the Python one.
- // Indeed, computing the divisors of 9007199254740992 was about 9x faster (23642ms on Python vs. 2641ms on C).
- int main(int argc, char** argv) {
- if (argc < 2) { // for some reason, argc is 1 if no arguments are specified.
- printf("Specify the number whose divisors you want to take as the first argument.");
- }
- unsigned long long num = 0;
- // The below "for" loop converts a string into an unsigned long long.
- // Say you input "123".
- // The loop:
- // - takes the character "1" (value 49), subtracts 48, gets 1.
- // - multiplies the number by 10 and adds 1 (result = 1).
- // - takes the character "2" (value 50), subtracts 48, gets 2.
- // - multiplies the number by 10 and adds 2 (result = 12).
- // - takes the character "3" (value 51), subtracts 48, gets 3.
- // - multiplies the number by 10 and adds 3 (result = 123).
- for (int i = 0; argv[1][i]; ++i) {
- num = argv[1][i]-48+num*10;
- }
- // i is an unsigned long because the square root of an unsigned long long will always be an unsigned long.
- for (unsigned long i = 1; num/i>=i; // This is the part that stops at the square root of the number.
- // When evaluating a non-square number:
- // 23 / 1 = 23
- // 23 / 2 = 11.5
- // 23 / 3 = 7.(6)
- // 23 / 4 = 5.75
- // 23 / 5 = 4.6
- // When evaluating a square number:
- // 25 / 1 = 25
- // 25 / 2 = 12.5
- // 25 / 3 = 8.(3)
- // 25 / 4 = 6.25
- // 25 / 5 = 5
- // We stop once the result, rounded down, is less than or equal to the divisor (the opposite of it being greater than the divisor).
- // In both examples, the square root of the number, rounded down, is the result of the final division rounded down.
- ++i) {
- if (num % i == 0) {
- printf("%lu\n",i);
- if (i * i != num) { // To avoid getting a duplicate result.
- printf("%llu\n",num/i);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement