Java Exercises: 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-dimension array (m x m) A[][] such that A[i][j] is false if I and j are prime otherwise A[i][j] becomes true.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;
public class Solution {
public static int prime_cell(int a, int b) {
if (a == 0 || b == 0) {
return 1;
}
if (a < b) {
int t = a;
a = b;
b = t;
}
if (a % b == 0)
{
return b;
}
else
{
return prime_cell(b, a % b);
}
}
public static void main(String[] args) {
int n = 3;
boolean[][] A = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = prime_cell(i, j) == 1;
System.out.print(A[i][j] + " ");
}
System.out.println();
}
}
}
Sample Output:
true true true true true true true true false
Flowchart:
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.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework