初心者がまとめるPython Programmingと時々数学

University of California Berkeleyに在籍中。自分用に勉強内容をまとめるブログ。

n進数とアルゴリズム Integer and Algorithms

10進数…decimal (base 10)

2進数…binary (base 2)

8進数…octal (base 8)

16進数…hexadecimal (base 16)

 

0から15までの変換表

f:id:xUshi:20180930113410p:plain

 

b: integer > 1, n: integer > 0, それぞれの進数は、次のようにして10進数で表せる。

f:id:xUshi:20180930083658p:plain

例:

The decimal expansion (base 10) of the integer that has f:id:xUshi:20180930083906p:plain as its binary expansion is

f:id:xUshi:20180930084726p:plain

101011111は9桁あるので最初のkはk=9-1=8、そして徐々に減っていき0に近づく。

その10のk乗に、それぞれの桁の数字をかける。9桁目なら1、8桁目なら0。

 

The decimal expansion of the number with dexadecimal expansion f:id:xUshi:20180930085557p:plain is

f:id:xUshi:20180930085836p:plain

2AE0Bは5桁なのでk=4から始まる。

5桁目は2なので、2・10の4乗。

 

16進数のそれぞれの桁は4ビットを表している(ビット…binary digitの略。1桁の2進数=1ビット。4ビット=4桁の2進数)。そして8ビットを1バイトといい、これが2桁の16進数に相当する。

 

次に、10進数からそれぞれの基数へ変換する場合。

10進数の数字を基数で割っていく。そしてその余りを最後から順番に並べたものがその基数での数字になる。

例: 

To find the octal expansion of f:id:xUshi:20180930110514p:plain

f:id:xUshi:20180930110950p:plain

Hence, f:id:xUshi:20180930111157p:plain

 

To find the hexadecimal expansion of f:id:xUshi:20180930111614p:plain,

f:id:xUshi:20180930111956p:plain

 

10進数以外での基数同士の変換。

例:

Find the octal and hexadecimal expansions of f:id:xUshi:20180930113658p:plain and the binary expansions of f:id:xUshi:20180930113836p:plain and f:id:xUshi:20180930113904p:plain.

8は2の3乗なので右から3桁ずつ。16は2の4乗なので4桁ずつ取る。

表を使うと簡単。

f:id:xUshi:20180930114903p:plain

 

f:id:xUshi:20180930115406p:plain

 

2進数の加法。

右端から順に足していき、係数×基数+余りの形に直していく。

余りを最後から順に組み合わせたものが加法の答えになる。

例:

Add a = f:id:xUshi:20180930132517p:plain, b = f:id:xUshi:20180930132536p:plain.

一番右端同士の足し算は、a0+b0=0+1=0・2+1

上記よりc0=0、s0=

次の位がa1+b1+c0=1+1+0=1・2+0

上記よりc1=1, s1=0

次の位がa2+b2+c1=1+0+1=1・2+0

c2=1, s2=0

a3+b3+c2=1+1+1=1・2+1

c3=1, s3=1s4=c3=1

∴ s = a + b = f:id:xUshi:20180930133530p:plainf:id:xUshi:20180930133629p:plain

 

2進数同士の掛け算。

2の累乗分だけ0を右側に付け足す。

例:

Find the product of f:id:xUshi:20180930134040p:plain.

f:id:xUshi:20180930135722p:plain

 

Modular Exponentiation

2進数を使って大きな数の余りを求める事が出来る。

b: integer, f:id:xUshi:20180930140914p:plain, m: positive integers

x := 1

power := b mod m

for i := 0 to k-1

      if ai = 1 then x := (x・power) mod m

      power := (power・power) mod m

return x{x equals f:id:xUshi:20180930141321p:plain}

例:

Use that algorithm to find f:id:xUshi:20180930144727p:plain.

f:id:xUshi:20180930144700p:plain

f:id:xUshi:20180930144821p:plain