c++ - FCTRL code chef too slow -
i having issues cpp code in code chef factorial problem. http://www.codechef.com/problems/fctrl keep getting error telling me slow, , wondering if there way speed up?
#include <iostream> using namespace std; int divisible_by_5(long &number) { long hold = 0; int result = 0; if(number % 5 == 0) { result++; hold = number/5; while(hold % 5 == 0) { result++; hold = hold/5; } } return result; } int factorial_expansion(long &number) { int result = 0; while(number > 4) { result += divisible_by_5(number); number--; } return result; } int main() { ios_base::sync_with_stdio(false); int *p_results_array; int lines; cin >> lines; p_results_array = new int [lines]; for(int = 0; < lines; i++) { long input; cin >> input; p_results_array[i] = factorial_expansion(input); } for(int = 0; < lines; i++) { cout << p_results_array[i] << endl; } return 0; }
edit ended revising everything, , turns out math could've been way better.
#include <iostream> #include <cmath> using namespace std; int main() { int lines; cin >> lines; while (lines--) { long input; cin >> input; int result = 0; (int = 1; pow(5, i) <= input; i++) result += input/pow(5, i); cout << result << endl; } return 0; }
you can several things speed up. hth.
one, separate inputs processing, in main
. can time algo, not typing speed. like
for(int = 0; < lines; i++) { long input; cin >> input; p_results_array[i] = input; } for(int = 0; < lines; i++) { p_results_array[i] = factorial_expansion( (long) p_results_array[i]); }
two, keep map of got don't have re-do calcs, such as
#include <map> map<long, long> fivepowers; // , later, check or set known answers
your divisible_by_5
can enhanced, somethng - , notice changed input type of const long&
retain functional interface
int divisible_by_5(const long &number) { long hold = number; int result = 0; while(hold % 5 == 0 ) { result++; hold = hold/5; if ( fivepowers.find(hold) != fivepowers.end() ) return fivepowers[hold] + result; } fivepowers[number] = result; return result; }
lastly, can improvise factorial_expansion
knowing answer 10,11,12,13,14 same 10. first pass, need find out how ahead of 5x are, , bring next number exact 5x. thereafter, reduce 5, not 1. so, math , programming.
int factorial_expansion(const long &number) { long hold = number; int result = 0; int adjuster = number % 5; if ( adjuster == 0 ) adjuster = 5; // else double-count while(hold > 4) { result += divisible_by_5(hold); hold -= adjuster; adjuster = 5; } return result; }
i curious timing get.
Comments
Post a Comment