w3resource

Java: Create a 2-D array such that A[i][j] is false if I and j are prime, otherwise true

Java Basic: Exercise-158 with Solution

Write a Java program to create a two-dimensional array (m x m) A[][] such that A[i][j] is false if I and j are prime otherwise A[i][j] becomes true.

Visual Presentation:

Java Basic Exercises: Create a two-dimension array (m x m) A[][] such that A[i][j] is true if I and j are prime and have no common factors.

Sample Solution:

Java Code:

import java.util.Scanner;

public class Solution {
    // Method to determine if two numbers are relatively prime
    public static int prime_cell(int a, int b) {
        // If either number is zero, return 1 as a special case
        if (a == 0 || b == 0) {
            return 1;
        }
        
        // If a is less than b, swap the values using a temporary variable
        if (a < b) {
            int t = a;
            a = b;
            b = t;
        }
        
        // Check if a is divisible by b
        if (a % b == 0) {
            return b; // Return b if it evenly divides a
        } else {
            return prime_cell(b, a % b); // Recursively call prime_cell method with b and the remainder of a/b
        }
    }

    public static void main(String[] args) {
        int n = 3; // Initialize variable 'n' with value 3
        boolean[][] A = new boolean[n][n]; // Create a 2D boolean array of size n x n
        
        // Loop through each element of the array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // Assign true if the result of prime_cell is 1 (relatively prime), otherwise assign false
                A[i][j] = prime_cell(i, j) == 1;
                System.out.print(A[i][j] + " "); // Print the value of the array element
            }
            System.out.println(); // Move to the next line after printing each row
        }
    }
} 

Sample Output:

true true true 
true true true 
true true false 

Flowchart:

Flowchart: Java exercises: Create a two-dimension array (m x m) A[][] such that A[i][j] is true if I and j are prime and have no common factors.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to prove that Euclid’s algorithm computes the greatest common divisor of two positive given integers.
Next: Write a Java program to find the k largest elements in a given array. Elements in the array can be in any order.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.