Follow posts tagged #prime number in seconds.
Sign upAlgorithm: Prime Numbers
To start off everything, I thought an easy and small algorithm would be good. Here I have a prime number algorithm to calculate whether a number is prime or not.
In this post I would be going over each step in the algorithm with an explanation of it all.
Here is the Code (number is a variable that can represent any number):
if (number % 2 == 0)
return false;
else
{
int divisor = 3;
while (divisor <= (int)(Math.Sqrt((double)(number)) + 1))
{
if (number % divisor == 0)
{
return false;
}
divisor = divisor + 2;
}
return true;
}
In the first line of Code, we check if the number divide by 2 leaves no remainder. The % operator (called the Modulo operator) is used to calculate the remainder of a divide problem. For example, 2 % 2 leaves a remainder of 0, since 2 / 2 is a whole number. So if number = 4, the first line of code will return false, since 4 % 2 = 0. If number % 2 != 0, it would go onto the else, and continue to run through the rest of the code. We initialize a new variable called divisor, which is what we divide each number by, to test if it is prime or not. The next line of code is a while loop with the condition of divisor < Math.Sqrt((double)number) + 1. This would run through so long as divisor is less than the Square Root of number + 1. We now test the number variable to see if it is dividable by some other prime numbers. Just like the first couple lines of code, we check if it can equally divide into 3. If it can, it would return false and increase the value of divisor by 2. After the loop is done and it has not returned false, it would return true since it cannot be divided into divisor.
That was the Prime Number Algorithm, made by me (o-notation). If you have any questions/suggestions, please message me.
Thanks.
掛け算のない世界
素数の話題が盛り上がっていたようなので,便乗する.素数とは,1とその数以外のどんな自然数によっても割り切れない数のことだ.で,普通は算術の基本定理の説明に入るわけだけれど,ちょっとひねくれて考えてみる.
そもそも,素数がなぜ素数なのかと言えば,掛け算があるからだ.ところが,自然数は足し算だけで定義できる.
1, 2, 3, … = 1, 1+1, 1+1+1, …
なのだから.
自然数の掛け算はごく自然な演算に思えるし,足し算→掛け算のステップをもう一段上れば冪乗という人類の英知の結晶のような演算にもたどり着ける.なので今更「掛け算は認めない」と叫んでも無益なわけだが,掛け算の無い世界を想像することは出来る.
それは,一言で言うと,純粋な「群」だ.群は要素に対して1種類(以上)の演算が定義されたもののことを言う.(正確には群ではなくマグマである.その他の「群もどき」についてはGroup-like structuresをご参照.)
群の性質を調べていくと,いろいろ興味深いことがわかる.例えば,ベクトルとベクトルは足し算が出来るので,ベクトルは群になる.それどころか,ベクトルの変換(平行移動とか,回転とか)も足し算が出来るので,変換もまた群になる.
オブジェクト指向プログラミング言語では,整数クラスというものが必ずあるものだが,さらにその基底クラスとして,足し算しかできない自然数というクラスを導入して,さらにそのインタフェース(プロトコル)を抜き出したものが,群(のひとつ)と言える(かもしれない).
めくるめく素数の世界も奥深いが,抽象度の階段を一歩登るのも興味深い.
![]()