Find powers of 3

I saw this question somewhere and thought I’d jot down an answer. I’m sure there’s a bit twiddling method to do this but I think this is about as fast as you’re going to get…

  int power_of_3(uint32_t n) {
    switch(n) {
      case 1: return 1;break;
      case 3: return 1;break;
      case 9: return 1;break;
      case 27: return 1;break;
      case 81: return 1;break;
      case 243: return 1;break;
      case 729: return 1;break;
      case 2187: return 1;break;
      case 6561: return 1;break;
      case 19683: return 1;break;
      case 59049: return 1;break;
      case 177147: return 1;break;
      case 531441: return 1;break;
      case 1594323: return 1;break;
      case 4782969: return 1;break;
      case 14348907: return 1;break;
      case 43046721: return 1;break;
      case 129140163: return 1;break;
      case 387420489: return 1;break;
      case 1162261467: return 1;break;
      case 3486784401: return 1;break;
    };  
    return 0;
  }
Please follow or like: