Advertisement
wintest

МАТРИЦА: Сума на простите елементи

Jan 14th, 2017
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <clocale>
  3. #include <ctime>
  4. #include <cmath>
  5.  
  6. using namespace std;
  7.  
  8. #define M 5
  9. #define N 5
  10.  
  11. int sumOfPrime(int array[][N], size_t rows);
  12. void fillTheArray(int array[][N], size_t rows);
  13. void printTheArray(int array[][N], size_t rows);
  14.  
  15. int main(){
  16.     setlocale(LC_ALL, "Bulgarian");
  17.     srand(time(NULL));
  18.  
  19.     int array[M][N];
  20.     fillTheArray(array, M);
  21.     printTheArray(array, M);
  22.     cout << endl;
  23.     cout << sumOfPrime(array, M);
  24.     return 0;
  25. }
  26. //К) намиране на сума на онези елементи от матрицата, които са прости числа;
  27. int sumOfPrime(int array[][N], size_t rows){
  28.     int sumOfPrime = 0;
  29.     for (size_t i = 0; i < M; i++)
  30.     {
  31.         for (size_t j = 0; j < N; j++){
  32.             if (array[i][j] == 1 || array[i][j] == 0){
  33.                 sumOfPrime += array[i][j];
  34.             }
  35.             else{
  36.                 bool isPrime = true;
  37.                 for (size_t n = 2; n <= array[i][j] / 2; n++)
  38.                 {
  39.                     if (array[i][j] % n == 0)
  40.                     {
  41.                         isPrime = false;
  42.                         break;
  43.                     }
  44.                 }
  45.                 if (isPrime) sumOfPrime += array[i][j];
  46.             }
  47.         }
  48.     }
  49.     return sumOfPrime;
  50. }
  51.  
  52. void fillTheArray(int array[][N], size_t rows){
  53.     for (size_t i = 0; i < M; i++)
  54.     {
  55.         for (size_t j = 0; j < N; j++){
  56.             array[i][j] = rand() % 5;
  57.  
  58.         }
  59.     }
  60. }
  61. //принтирам масив
  62. void printTheArray(int array[][N], size_t rows){
  63.     cout << "Оригиналната матрица е това : " << endl;
  64.  
  65.     for (size_t i = 0; i < M; i++)
  66.     {
  67.         for (size_t j = 0; j < N; j++){
  68.             cout << array[i][j] << "\t";
  69.         }
  70.         cout << endl;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement