none
faster power of ints, fast int digits count, usefull RRS feed

  • General discussion

  • //3 times faster then math.pow

    private static int FastPow(int x, int y) { switch (y) { case 0: return 1; case 1: return x; case 2: return x * x; case 3: return x * x * x; case 4: return x * x * x * x; case 5: return x * x * x * x * x; case 6: return x * x * x * x * x * x; case 7: return x * x * x * x * x * x * x; case 8: return x * x * x * x * x * x * x * x; case 9: return x * x * x * x * x * x * x * x * x; case 10: return x * x * x * x * x * x * x * x * x * x; } int n = Math.Abs(y); for (int z = 1; ; x *= x) { if ((n & 1) != 0) z *= x; if ((n >>= 1) == 0) return (y < 0 ? 1 / z : z); } } private int GetDigitCount(int value) { if (value == 0) { return 1; } int sign = 0; if (value < 0) { value = -value; sign = 1; } if (value <= 9) { return sign + 1; } if (value <= 99) { return sign + 2; } if (value <= 999) { return sign + 3; } if (value <= 9999) { return sign + 4; } if (value <= 99999) { return sign + 5; } if (value <= 999999) { return sign + 6; } if (value <= 9999999) { return sign + 7; } if (value <= 99999999) { return sign + 8; } if (value <= 999999999) { return sign + 9; } return sign + 10; }



    • Edited by igalk474 Tuesday, June 12, 2012 6:53 PM
    Tuesday, June 12, 2012 6:52 PM

All replies

  • In 18 years of coding I've only needed to know the number of digits in an int once :-)  But thanks, i'll be ready if it ever comes up again.


    This signature unintentionally left blank.

    Wednesday, June 13, 2012 6:55 PM