【Javascript】素数がわかる表をピラミッド式で作ってみる

左上を中心に数字をピラミッド式に展開していく。

素数の表


var min_num = 1;
var max_num = 144;
var num = 1;
var pos_mode = "x"; //"x" or "y"
var pos_y = 1;
var pos_x = 1;
var num_arr = new Array();
for(i = min_num;i <= max_num;i++){
if(num_arr[pos_x] == null){
num_arr[pos_x] = new Array();
}
num_arr[pos_x][pos_y] = i;
if(max_num == i){
break;
}
if(pos_x == 1 ){
pos_mode = "y";
pos_x = num + 1;
pos_y = 1;
num += 1;
continue;
}
if(pos_mode == "y"){
pos_y++;
if(pos_y == num ){
pos_mode = "x";
}
continue;
}
if(pos_mode == "x"){
pos_x--;
continue;
}
}
document.write('<table border="1">');
for(y = 1;y <= num;y++){
document.write('<tr>');
for(x = 1;x <= num;x++){
var num1 = num_arr[x][y];
var prime1 = isPrime(num1);
var bgcolor = "";
if(prime1 == 1){
bgcolor = 'background-color:yellow;';
}
document.write('<td align="center" style="' + bgcolor + 'width:40;height:40;vertical-align:"middle";>' + num1 + '</td>');
}
document.write('</tr>');
}
document.write('</table>');
function isPrime(num){
var i;
if(num < 2){
return 0;
}else if(num == 2){
return 1; //素数
}
if(num % 2 == 0){
return 0;
}
for(i = 3; i*i <= num; i+=2){
if(num % i == 0){
return 0;
}
}
return 1; //素数
}