hey, so I have been working on project euler again, and I have been putting all of my non-problem functions under the namespace utility_functions. What should I do to improve clarity, and what would be a better name for this namespace?
Also, what is wrong with sum_of_divisors()? It consistently gives low values. The formula is from http://planetmath.org/FormulaForSumOfDivisors.html
Code:#ifndef utility_functions #define utility_functions #include <vector> #include <cstdlib> #include <cmath> using namespace std; namespace utility_functions { long long sqrt_number; long long number; void set_common_numbers(long long number_in) { sqrt_number = sqrt(number_in); number = number_in; return; } bool is_prime(long long number_in) { set_common_numbers(number_in); if(number == 0 || number == 1) return 0; for(long long b = 2; b < sqrt_number; b++) { if(number % b == 0) return 0; } return 1; } int smallest_divisor(long long number_in) { int my_sqrt_number = sqrt(number_in); for(long long a = 2; a < my_sqrt_number; a++) if(number_in % a == 0) return a; return number_in; } vector<short> prime_factor_field() //returns a vector of shorts that tell the multiplicity of each prime factor up to the square root of the number { vector<short> factor_field (sqrt_number, 0); bool all_prime_factors_found = 0; long long working_number = number; while(!all_prime_factors_found) { int current_factor = smallest_divisor(working_number); if(current_factor == working_number) { all_prime_factors_found = true; } else { factor_field[current_factor]++; working_number /= current_factor; } } return factor_field; } long long number_of_divisors(long long number_in) { set_common_numbers(number_in); int divisors = 2; vector<short> factor_field = prime_factor_field(); for(int a = 0; a < sqrt_number; a++) divisors *= factor_field[a] + 1; return divisors; } long long sum_of_divisors(long long number_in) { set_common_numbers(number_in); int sum = 1; vector<short> factor_field = prime_factor_field(); for(int a = 2; a < sqrt_number; a++) { if(factor_field[a] > 0) { sum *= (pow(a, factor_field[a] + 1) - 1) / (a - 1); } } return sum; } } #endif