Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to fill a matrix with prime numbers in Node.js

1 Answer

0 votes
function isPrime(num) {
    for (let i = 2; i <= parseInt(num / 2); i++) {
        if (num % i == 0) {
            return false;
        }
    }
    
    return true;
}
    
function fill_matrix_with_prime_number(matrix) {
    let rows = matrix.length;
    let cols = matrix[0].length;
    let total = rows * cols;
    let result = Array(total).fill(0);
    let index = 0;
    let num = 2;
    
    while (index < total) {
        if (isPrime(num) == true) {
            result[index] = num;
            index++;
        }
        num++;
    }
    
    index = 0;
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            matrix[i][j] = result[index];
            index++;
        }
    }
}

let rows = 5;
let cols = 6;
let matrix = Array(rows).fill(0).map(()=>new Array(cols).fill(0));

fill_matrix_with_prime_number(matrix);

for (let i = 0; i < rows; i++)  {
    let str = "";
    for (let j = 0; j < cols; j++) {
        str += matrix[i][j] + " ";
    }
    console.log(str);
}




/*
run:

2 3 5 7 11 13 
17 19 23 29 31 37 
41 43 47 53 59 61 
67 71 73 79 83 89 
97 101 103 107 109 113 

*/

 



answered Feb 17, 2024 by avibootz

Related questions

...