problem 5 states that the smallest number that is devisable by all the integers between 1 and 10 is 2520 and asks the question what is the smallest number that is devisable by all the integers between 1 and 20.
here is my soloution
to answer the above question the user obviously has to enter 20 (answer is 232,792,560)Code:#include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_NUM 500000000 int divide(long int num, int divisor); int main() { int result, max_divisor; long int num_divide; clock_t start, finish; printf("Please enter the max number to divide by: "); scanf(" %d", &max_divisor); start = clock(); for (num_divide = max_divisor; num_divide < MAX_NUM; num_divide += max_divisor) { if((result = divide(num_divide, max_divisor))) { break; } } finish = clock(); if (result == -1) { printf("\nnaughty naughty you entered zero you cant divide by zero!\n"); } else if (result == 0) { printf("\nthere is no number between 1 and %d that can be divided by all the integers 1 to %d\n", MAX_NUM, max_divisor); } else { printf("\nthe smallest number that can be divided by all the integers 1 to %d is %ld\n", max_divisor, num_divide); } printf("\ntime taken is %.6f seconds\n", (double)(finish - start) / (double)CLOCKS_PER_SEC); return 0; } int divide(long int num, int divisor) { // sanity checks if (num == 0) { return - 1; } if (num % divisor != 0) { return 0; } if (divisor == 2 && num % divisor == 0) { return 1; } return divide(num, divisor - 1); }
however i decided to calculate the time taken to work it out. and here comes the surprise while i do get slightly different results for each time i enter the same number (1000ths of a second) the time taken isn't linear for example it takes longer to compute max_devisor = 19 than max_devisor = 22 by roughly 0.04 seconds. why?
coop