Advertisement
marie_j

HW4-10

Apr 5th, 2020
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.42 KB | None | 0 0
  1. package ru.itsjava.arrays.homework;
  2.  
  3. // Задание:
  4. // а) создать в двухмерном массиве 3х3 простейший магический квадрат таким образом, чтобы введённое пользователем число находилось в центральной клетке;
  5. // б) вывести квадрат и его магическую константу;
  6. // в) определить, есть ли в квадрате простые числа, и вывести их.
  7.  
  8. import java.util.Scanner;
  9.  
  10. public class Homework4_10 {
  11.     public static void main(String[] args) {
  12.         int[][] magicSquare = new int[3][3];
  13.         Scanner console = new Scanner(System.in);
  14.         System.out.println("Введите число.");
  15.         magicSquare[1][1] = console.nextInt();
  16.         magicSquare[0][0] = magicSquare[1][1] - 3;
  17.         magicSquare[0][1] = magicSquare[1][1] + 2;
  18.         magicSquare[0][2] = magicSquare[1][1] + 1;
  19.         magicSquare[1][0] = magicSquare[1][1] + 4;
  20.         magicSquare[1][2] = magicSquare[1][1] - 4;
  21.         magicSquare[2][0] = magicSquare[1][1] - 1;
  22.         magicSquare[2][1] = magicSquare[1][1] - 2;
  23.         magicSquare[2][2] = magicSquare[1][1] + 3;
  24.         System.out.println("Магический квадрат:");
  25.         for (int i = 0; i < 3; i++) {
  26.             for (int j = 0; j < 3; j++) {
  27.                 System.out.print(magicSquare[i][j] + "  ");
  28.             }
  29.             System.out.println();
  30.         }
  31.         System.out.println("Магическая константа: " + (magicSquare[0][0] + magicSquare[1][1] + magicSquare[2][2]));
  32.         System.out.print("Простые числа в квадрате: ");
  33.         boolean isNoSimpleNumbers = true;
  34.         for (int i = 0; i < 3; i++) {
  35.             for (int j = 0; j < 3; j++) {
  36.                 int numberOfDivisors = 0;
  37.                 for (int k = 1; k <= magicSquare[i][j]; k++) {
  38.                     if (magicSquare[i][j] % k == 0) {
  39.                         numberOfDivisors = numberOfDivisors + 1;
  40.                     }
  41.                 }
  42.                 if (numberOfDivisors < 3) {
  43.                     System.out.print(" " + magicSquare[i][j] + " ");
  44.                     isNoSimpleNumbers = false;
  45.                 }
  46.             }
  47.         }
  48.         if (isNoSimpleNumbers) {
  49.             System.out.println(" отсутствуют.");
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement