Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1546725
  • 博文数量: 327
  • 博客积分: 10000
  • 博客等级: 上将
  • 技术积分: 3556
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-05 21:28
个人简介

东黑布衣,流浪幽燕。 真诚善良,值得信赖。

文章分类

全部博文(327)

我的朋友

分类: BSD

2018-02-05 14:55:01



  1. //

  2. #include "stdafx.h"
  3. #include <stdio.h>
  4. #include <math.h>

  5. int isPowerOfTwo(int n)//231
  6. {
  7.     if(n<=0)return 0;
  8.     if(0==(n&(n-1))){
  9.         return 1;
  10.     }else
  11.         return 0;
  12. }

  13. int isPowerOfThree(int n)//326
  14. { //int范围内最大的3的幂是多少?1162261467
  15.     //3 9 27 81
  16.     //big3 % n ==0
  17.     //big3=3^k
  18.     //k=log3(maxint)
  19.     if(n<=0)return 0;
  20.     const int maxint=0x7FFFFFFF;
  21.     int k=(int)log((long double)maxint)/log((long double)3);//这种方法仅对素数有用
  22.     int big3=pow((double)3,(double)k);
  23.     printf("big3 is %d\n",big3);
  24.     return (big3%n ==0);
  25. }

  26. int isPowerOfFour(int n)//342
  27. {
  28.     //2 8 false 2=10 8=1000
  29.     //4 16 true
  30.     //5=101

  31.     //0101 & 8 1000 = 0000
  32.     //0101 & 4 0100 = 0100
  33.     if(n<=0)return 0;
  34.     if((n&(n-1))==0 && (n&0x55555555)){
  35.         return 1;
  36.     }else{
  37.         return 0;
  38.     }
  39. }

  40. int _tmain(int argc, _TCHAR* argv[])
  41. {
  42.     int x;
  43.     scanf("%d",&x);
  44.     do{
  45.         if(isPowerOfTwo(x)){
  46.             printf("x is power of 2\n");
  47.         }else{
  48.             printf("x is not power of 2\n");
  49.         }
  50.         if(isPowerOfThree(x)){
  51.             printf("x is power of 3\n");
  52.         }else{
  53.             printf("x is not power of 3\n");
  54.         }
  55.         if(isPowerOfFour(x)){
  56.             printf("x is power of 4\n");
  57.         }else{
  58.             printf("x is not power of 4\n");
  59.         }
  60.         scanf("%d",&x);
  61.     }while(x!=-1);
  62.     return 0;
  63. }

阅读(1434) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~