Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.8 kB
1
Indexable
Never
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

bool isPrime(int num) {
    if (num <= 1) return false;
    if (num == 2) return true;
    if (num % 2 == 0) return false;

    int sqrtNum = sqrt(num);
    for (int i = 3; i <= sqrtNum; i += 2) {
        if (num % i == 0) return false;
    }
    return true;
}

vector<vector<int>> generateSpiralPrimeMatrix(int N) {
    vector<vector<int>> matrix(N, vector<int>(N, 0));

    int rowStart = 0, rowEnd = N - 1;
    int colStart = 0, colEnd = N - 1;
    int num = 2;

    while (rowStart <= rowEnd && colStart <= colEnd) {
        // Fill top row
        for (int i = colStart; i <= colEnd; ++i) {
            if (isPrime(num)) {
                matrix[rowStart][i] = num++;
            }
        }
        ++rowStart;

        // Fill rightmost column
        for (int i = rowStart; i <= rowEnd; ++i) {
            if (isPrime(num)) {
                matrix[i][colEnd] = num++;
            }
        }
        --colEnd;

        // Fill bottom row
        for (int i = colEnd; i >= colStart; --i) {
            if (isPrime(num)) {
                matrix[rowEnd][i] = num++;
            }
        }
        --rowEnd;

        // Fill leftmost column
        for (int i = rowEnd; i >= rowStart; --i) {
            if (isPrime(num)) {
                matrix[i][colStart] = num++;
            }
        }
        ++colStart;
    }

    return matrix;
}

int main() {
    int N;
    cout << "Nhap cap N cua ma tran xoan oc nguyen to: ";
    cin >> N;

    vector<vector<int>> spiralPrimeMatrix = generateSpiralPrimeMatrix(N);

    cout << "Ma tran xoan oc nguyen to cap " << N << " la:\n";
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            cout << spiralPrimeMatrix[i][j] << "\t";
        }
        cout << endl;
    }

    return 0;
}