Advertisement
sailorbob74133

Maman 12 Q3 in C

Nov 18th, 2012
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.93 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // slowest
  4. int dCount1(unsigned int t1) {
  5.     int t2=0;
  6.     do {
  7.         ++t2;
  8.     } while ( ( t1 = t1 / 10 ) != 0 ) ;
  9.     return t2;
  10. }
  11.  
  12. // better since mul is faster than integer divide
  13. int dCount2 (unsigned int t1) {
  14.     int t2 = 0, t3 = 1;
  15.  
  16.     while ( t3 <= t1 ) {
  17.         ++t2;
  18.         t3 *= 10;
  19.     }    
  20.     return t2;
  21. }
  22.  
  23. // best since array will be in L1 cache after first use so we just have an
  24. // increment and comparison.
  25. int dCount3(unsigned int t1) {
  26.     unsigned int sizes[] = { 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
  27.  
  28.     int t2 = 10;
  29.    
  30.     while ( t1 < sizes[t2] ) t2--;
  31.  
  32.     return t2;
  33. }
  34.  
  35. int main(void) {
  36.     unsigned int t1;
  37.     char *str = "%d digits\n";
  38.  
  39.     while( scanf("%u", &t1) != EOF && t1 != 0 ) {
  40.         printf(str, dCount1(t1));
  41.         printf(str, dCount2(t1));
  42.         printf(str, dCount3(t1));
  43.     }
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement