エラトステネスのふるい(素数の枚挙)

prime[i]は、iが素数であればtrueの値をもつ。

program sieve(input,output);
const n = 1000;
var i, j : integer;
   prime : array [2..n] of boolean;
begin
   for i := 2 to n do prime[i] := true;
   for i := 2 to trunc(sqrt(n)) do
      if prime[i] = true then
      begin
	 j := i + i;
	 while j <= n do
	 begin
	    prime[j] := false;
	    j := j + i
	 end
      end;
   for i := 2 to n do if prime[i] = true then write(i);
   writeln
end.

多次元配列

配列を用いれば tex2html_wrap_inline28 行列をプログラムの中で扱うことができます。

tex2html_wrap_inline30 行列とは、n次元ベクトルが、m個ならんだものでした。n次元ベ クトルのデータを表現する型は

type line = array [1..n] of real;
でした。そしてこれがm個ならんだデータの型は、
type line = array [1..n] of real;
     matrix = array [1..m] of line;
となるわけです。特に、行だけ格納する変数を使用するようなことがなければ、
type matrix = array [1..m] of array [1..n] of real;
と書いてもかまいません。さらに、Pascalでは次のように省略できることになっ てます。
type matrix = array [1..m, 1..n] of real;

次のような変数宣言があったとします。

var a : matrix;
変数aには行列を表現するデータが格納されるわけです。 添字付変数
a[2]
には、その配列の2行目の「行」が格納されています。さらに、 添字付き変数
a[2][3]
には、その配列の2行目3列目の要素が格納されています。 したがって、2行目3列目のところを0にしたいときには、
a[2][3] := 0
でよいわけです。また、添字付変数にもコンマによる省略記法が用意されてい ます。上の添字付変数は
a[2,3]
と書いても構いません。

さてこのような配列の操作について考えてみましょう。

基本形パターンは

    for i := 1 to n do 
      for j := 1 to n do 
        〜 a[i,j] 〜
です。

行列への値の入力

...
const n = 5;
type index = 1..n;
     matrix = array [index, index] of real;
var a : matrix; i,j : index;
...
begin
...
    for i := 1 to n do 
      for j := 1 to n do 
        read(a[i,j]);
...

単位行列に初期化

    for i := 1 to n do 
      for j := 1 to n do 
        if i = j then a[i,j] := 1 else a[i,j] := 0;

練習

行列のマイナス(符号の反転)を考えてみなさい。

配列値のコピー

...
const n = 5;
type index = 1..n;
     matrix = array [index, index] of real;
var a, b: matrix; i,j : index;
...
begin
...
    for i := 1 to n do 
      for j := 1 to n do 
        a[i,j] := b[i,j];
...
とする必要はなく、単に
a := b
でよい。

行列の加法

for i := 1 to n do
  for j := 1 to n do
      c[i,j] := a[i,j] + b[i,j]

行列の乗法

\begin{verbatim}
...
const n = 5;
type index = 1..n;
     matrix = array [index, index] of real;
var a, b: matrix; i,j,k : index;
    x : real;
...
begin
...
   for i := 1 to n do j := 1 to n do
     x := 0;
     for k := 1 to n do 
       x := x + a[i,k] * b[k,j];
     c[i,j] := x;




Tue Jul 15 23:24:42 JST 1997