Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.itsjava.arrays.homework;
- // Задание:
- // а) создать в двухмерном массиве 3х3 простейший магический квадрат таким образом, чтобы введённое пользователем число находилось в центральной клетке;
- // б) вывести квадрат и его магическую константу;
- // в) определить, есть ли в квадрате простые числа, и вывести их.
- import java.util.Scanner;
- public class Homework4_10 {
- public static void main(String[] args) {
- int[][] magicSquare = new int[3][3];
- Scanner console = new Scanner(System.in);
- System.out.println("Введите число.");
- magicSquare[1][1] = console.nextInt();
- magicSquare[0][0] = magicSquare[1][1] - 3;
- magicSquare[0][1] = magicSquare[1][1] + 2;
- magicSquare[0][2] = magicSquare[1][1] + 1;
- magicSquare[1][0] = magicSquare[1][1] + 4;
- magicSquare[1][2] = magicSquare[1][1] - 4;
- magicSquare[2][0] = magicSquare[1][1] - 1;
- magicSquare[2][1] = magicSquare[1][1] - 2;
- magicSquare[2][2] = magicSquare[1][1] + 3;
- System.out.println("Магический квадрат:");
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- System.out.print(magicSquare[i][j] + " ");
- }
- System.out.println();
- }
- System.out.println("Магическая константа: " + (magicSquare[0][0] + magicSquare[1][1] + magicSquare[2][2]));
- System.out.print("Простые числа в квадрате: ");
- boolean isNoSimpleNumbers = true;
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- int numberOfDivisors = 0;
- for (int k = 1; k <= magicSquare[i][j]; k++) {
- if (magicSquare[i][j] % k == 0) {
- numberOfDivisors = numberOfDivisors + 1;
- }
- }
- if (numberOfDivisors < 3) {
- System.out.print(" " + magicSquare[i][j] + " ");
- isNoSimpleNumbers = false;
- }
- }
- }
- if (isNoSimpleNumbers) {
- System.out.println(" отсутствуют.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement