不使用 操作符求乙個數的1 3

2021-06-08 11:44:30 字數 2471 閱讀 2026

問:在不使用*、/、+、-、%操作符的情況下,如何求乙個數的1/3?(用c語言實現)

第一種方法:使用位操作符並實現「+」操作

// 替換加法運算子 

int add(int x, int y)  while (a); 

return b; 

} int divideby3 (int num)  

if (num == 3) 

sum = add(sum, 1); 

return sum;  

}

原理:n = 4 * a + b; n / 3 = a + (a + b) / 3; 然後 sum += a, n = a + b 並迭代; 當 a == 0 (n < 4)時,sum += floor(n / 3); i.e. 1, if n == 3, else 0

第二種方法:

#include 

#include 

int main() 

第三種方法:

log(pow(exp(number),0.33333333333333333333)) /* :-) */

增強版:

log(pow(exp(number),sin(atan2(1,sqrt(8)))))  

第四種方法:

#include 

#include 

int main(int argc, char *argv) 

第五種方法:使用內聯彙編

#include <

stdio.h

>

int main()  

第六種方法:

// 注意: itoa 不是個標準函式,但它可以實現

// don't seem to handle negative when base != 10

int div3(int i)  

第七種方法:

unsigned div_by(unsigned const x, unsigned const by)  

return floor; 

}

替換掉上面演算法的++運算子:

unsigned inc(unsigned x)  

return 0; // 溢位(注意:這裡的x和mask都是0)

}

這個版本更快一些:

unsigned add(char

const zero, unsigned const x, unsigned const y)  

unsigned div_by(unsigned const x, unsigned const by)  

return floor; 

}

第八種方法:實現乘法

int mul(int

const x, int

const y) [x]); 

}

第九種方法:極限

public

static

int div_by_3(long a)  

return (int) (a >> 32); 

} public

static

long add(long a, long b)  

原理:

因為, 1/3 = 1/4 + 1/16 + 1/64 + ...

所以,a/3 = a * 1/3  

a/3 = a * (1/4 + 1/16 + 1/64 + ...)

a/3 = a/4 + a/16 + 1/64 + ...

a/3 = a >> 2 + a >> 4 + a >> 6 + ...

第十種方法:

public static int divideby3(int a)  

sub >

>= 1; 

threes >

>= 1; 

} if (negative) result = negate(result); 

return result; 

} public static int negate(int a)  

public static int add(int a, int b)  

return x; 

}

注:本例是c#實現,因為作者更熟悉c#,但本題更傾向於演算法,所以語言並不是太重要吧?(當然只是在不使用語言特性的前提下。)

不使用 操作符求乙個數的1 3

發表於 2012 08 07 10 08 csdn 王然智慧型演算法 彙編程式設計c 摘要 演算法一直是程式設計師高階的一道龍門,通常演算法都是為了更高效地解決問題而創造的,但也有的只是出於學術性,並不在意其實際意義。這是近日在國外技術問答 stackoverflow的乙個熱門問題,不知道你能給出幾...

C語言 統計乙個數中1的個數 移位操作符

移位運算子是將資料看成二進位制數,對其進行向左或向右移動若干位的運算。位移位運算子分為 右移和 移位時,移出的位數全部丟棄,移出的空位補入的數與左移還是右移花接木有關。如果是左移,則規定補入的數全部是0 如果是右移,還與被移位的資料是否帶符號有關。若是不帶符號數,則補入的數全部0 若是帶符號數,則補...

求乙個數約數的個數

求約數的個數 計算乙個整數的約數個數 輸入格式 輸入乙個整數 輸出格式 輸出一行,為輸入整數的約數的個數 樣例輸入 10 樣例輸出 4ac import math number int raw input count 0 sqrt float math.sqrt number if number s...