Printing a triangle of prime numbers using for loop - java

I am trying to make a triangle of prime numbers .. the number of rows will be user defined
for example if user gives "4" as number of rows then the program should show a triangle of prime numbers containing 4 rows
input :4
output :
2
3 5
7 11 13
17 19 23 29

These are two tasks: get the list of primes (or just something like nextPrime(int)) and get the triangle, both are very simple.
For the implementation of first, you may look at Next Prime number Java only working with certain numbers
For the implementation of second, just do something like:
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
nextPrime = ...
System.out.print (nextPrime + " ");
}
System.out.println ();
}

Let say you already have your primes (sufficient amount).
int[] primes = ...;
Then for N strings create array is StringBuilders and fill them up with your numbers:
StringBuilder[] builders = new StringBuilder[N];
int count = 0;
for(int row = 0; row < N; row++) {
int size = row + 1;
builders[row] = new StringBuilder();
for(int i = 0; i < size; i++) {
builders[row].append(primes[count++]);
builders[row].append(' ');
}
}
And then you may print them
for(StringBuilder sb : builders)
System.out.println(sb);

//please try these
import java.util.*;
public class primePtt1
{
public static boolean isPrimeNumber(int num) {
int c=0;
for (int i = 1; i <= num; i++) {
if (num % i == 0)
c++;
}
if (c==2)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter no. of rows : ");
int rows = sc.nextInt();
int counter = 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
/* Try to find next prime number by incrementing counter and testing it for primality */
while(!isPrimeNumber(counter)){
counter++;
}
System.out.print(counter+" ");
counter++;
}
System.out.println();
}
}
}

Related

How do i put the total sum of prime numbers first, then the prime numbers below it

I'm currently using this code, and I'm trying to output the total sum of how many prime numbers first and then the prime numbers list
Here is my code:
import java.util.*;
public class PrimeTime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j < i; j++) {
if (i%j == 0)
f = 1;
}
if (f == 0) {
System.out.print(i+ " ");
s = s +1;
}
}
System.out.println("N =" +s);
}
}
This is the result I get:
Input number: 10
2 3 5 7 N = 4
But what I'm looking for is this result:
Input number: 10
N = 4
2 3 5 7
I don't know how, I tried putting the S.O.P in different places and I can't figure out how.
If you want to display N = 4 before 2 3 5 7, you can append the numbers (i.e. 2 3 5 7) to a StringBuilder and print the same after printing N = 4 e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
StringBuilder numbers = new StringBuilder();
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0)
f = 1;
}
if (f == 0) {
numbers.append(i).append(' ');// Append to StringBuilder instead of printing
s = s + 1;
}
}
System.out.println("N =" + s);
System.out.println(numbers);
}
}
A sample run:
Input number: 10
N =4
2 3 5 7
Note: for checking the primality, checking up to Math.sqrt(i) is sufficient i.e. you should replace j < i with j <= Math.sqrt(i).
You can store the numbers in a list and then print them after the loop is over
Don't worry if you have not studied lists yet cause you will have to soon anyways.
here's the code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
LinkedList<Integer> list = new LinkedList<>();
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j < i; j++) {
if (i%j == 0)
f = 1;
}
if (f == 0) {
//System.out.print(i+ " ");
list.add(i);
s = s +1;
}
}
System.out.println("N = " +s);
for(int i = 0; i<list.size(); i++ ) {
System.out.print(list.get(i) + " ");
}
}

Number Triangles with alternating number

Hello All,
I was wondering if someone could help me with making a number triangle in Java that looks like the one below using nested while loops. Would someone be able to help me out?
4
56
789
1234
56789
I have a variable 'i' on the outer loop determining how many rows the triangle will be and a variable 'j' on the inner loop determine which number the triangle will begin with. the numbers have to stay between [1-9].
Can anyone help me out?
Try This, It Will Work... It accepts rows & number through user and in first for loop it runs the loop till the number of rows and second loop print the number as per the value of I in pattern and if condition to check if the number is 10 then reset the number with 1 to start the numbering again.
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
int rows, number = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no of rows");
rows = sc.nextInt();
System.out.println("Enter no to start with");
number = sc.nextInt();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
++number;
if (number == 10) {
number = 1;
}
}
System.out.println();
}
}
}
Try.. r is for number of rows and v is the value
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int v = sc.nextInt();
int i = v - 1;
int j = 1;
while(j != r + 1){
int k = 0;
int ans = 0;
while( k < j){
i = i + 1;
if(i == 10){
i = 1;
}
ans = ans * 10 + i;
k = k + 1;
}
System.out.println(ans);
j = j + 1;
}

2D Array: Magic Square

The question I am working on is:
A square with the side length n is filled with numbers 1,2,3,...n2 is a magic square if the sum of elements in each row, column, and two diagonals is the same value.
Write a program that reads in a value of 16 values from the keyboard and tests whether they form a magic square when put into a 4 x 4 array. You need to test the following 2 features:
Does each number of 1,2,...16 occur in user input? Tell the user to try again if they enter a number that they've already entered.
When the numbers are put into a square, are the sums of rows, columns, and diagonals equal to each other?
It must be done using two-dimensional array
I am having trouble with asking the user to try again if they enter a number that they have previously entered. And, numbers in 4 x 4 do not print.
What am I doing wrong? How can I fix it?
This is the code I have so far:
Scanner in = new Scanner (System.in);
int n =4;
int[][] square = new int[n][n];
int number = 0;
int num = 0;
for (int i = 0; i <16; i++){
number = num;
System.out.print ("Enter a number: ");
num = in.nextInt();
int num_2 = 0;
if (number==num || number==num_2) {
System.out.println ("Try again.");
System.out.println ("Enter a number: ");
num_2 = in.nextInt();
}
if (num > 16){
System.out.println ("Try again.");
break;
}
}
for (int i= 0; i < n; i++){
for (int j = 0; j < n; j++) {
num+=square [i][j];
System.out.print(square[i][j] + "\t");
}
}
}
}
You can try this code for 1st feature and add code for 2nd one.
int ar[][] = new int[4][4];
System.out.println("Enter Numbers");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
boolean flag = false;
int num = sc.nextInt();
if (num > 16 || num < 1) {
System.out.println("Please Enter number between 1 to 16");
flag=true;
j--;
} else {
for (int k = 0; k <= i; k++) {
for (int l = 0; l <= j; l++) {
if (ar[k][l] == num) {
System.out.println("This number already inserted...Please give another");
j--;
flag = true;
}
}
}
}
if (!flag) {
ar[i][j] = num;
}
}
}
If you can't understand anything please ask.
Hope this help.

Decent number program terminated

Actually I wrote a program for to find the decent number..
A Decent Number has the following properties:
3, 5, or both as its digits. No other digit is allowed.
Number of times 3 appears is divisible by 5.
Number of times 5 appears is divisible by 3.
Input Format:
The 1st line will contain an integer T, the number of test cases. This is followed by T lines, each containing an integer N. i.e. the number of digits in the number.
Output Format:
Largest Decent Number having N digits. If no such number exists, tell Sherlock that he is wrong and print −1.
Constraints
1≤T≤20,
1≤N≤100000
public class TrySamp {
public static void main(String[] args) throws ParseException {
Scanner scan = new Scanner(System.in);
long n = scan.nextInt();
List<Long> list = new ArrayList<Long>();
for (long i = 0; i < n; i++) {
list.add(scan.nextLong());
}
for (int i = 0; i < list.size(); i++) {
long s = list.get(i);
long c = 5 * ((2 * s) % 3);
System.out.println(c);
if (c > s) {
System.out.print(-1);
} else {
int o=1;
System.out.println("=="+ (o <= (s - c)));
for (int j = 1; j <= (s - c); j++) {
System.out.print(5);
}
for (int k = 1; k <= c; k++) {
System.out.print(3);
}
}
System.out.println("lo");
}
}
}
The program works fine for the sample input
Sample Input:
4 1 3 5 11
Sample Output
-1 555 33333 55555533333
but the program terminates when I give the input as
1 100000
or
1 10000
can anyone suggest me a method to solve this problem??..
I got your problem, Eclipse does not allows you to print such large numbers on your console.
If you try to run the program in console it will work as expected.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long n = scan.nextInt();
List<Long> list = new ArrayList<Long>();
for (long i = 0; i < n; i++) {
list.add(scan.nextLong());
}
for (int i = 0; i < list.size(); i++) {
long s = list.get(i);
long c = 5 * ((2 * s) % 3);
if (c > s) {
System.out.print(-1);
System.out.println();
} else {
int o = 1;
for (int j = 1; j <= (s - c); j++) {
System.out.print(5);
}
for (int k = 1; k <= c; k++) {
System.out.print(3);
}
System.out.println();
}
}
}

how to find prime number in 2d array and copy these numbers to another array

i have a code that create 2d array by asking user to enter the input than the system check if the elements are prime or not and if they are prime the system will copy them to an 1d array.
i can create the 2d array but i am stuck in the checking on the prime number and copied to a second array
this is the code
package question6;
import java.util.Scanner;
public class MtrixPrime {
public static void main(String[] args) {
int rows;
int cols;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row");
rows = sc.nextInt();
System.out.println("Enter number of column");
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
int[] array = new int[rows];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(matrix[i][j] % matrix[i][j] ==0 && matrix[i][j] %1 == 0){
////here i am stuck can anyone help me ??
array[i * j];
}
matrix[i][j] = sc.nextInt();
}
}
for(int row = 0 ;row<matrix.length; row++){
for(int col = 0 ; col< matrix.length; col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
I know it's old post but this might help others.
Used isPrime a boolean flag to save the state of matrix[i][j] value.
If reminder is 0 isPrime will hold false state of matrix[i][j].
Everything is similar like finding prime number of single number. Just have to use 3 for loops for matrix index, before that I have taken matrix values separately.
here's the code.
public static void main(String[] args) {
int rows, cols, remainder;
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row and colums : ");
rows = sc.nextInt();
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = sc.nextInt();
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
for (int k = 2; k <= matrix[i][j] / 2; k++) {
remainder = matrix[i][j] % k;
if (remainder == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(matrix[i][j] + " is a Prime number");
} else
System.out.println(matrix[i][j] + " is not a Prime number");
}
}
}
One tricky thing to look out for is that since you don't know how many primes you're going to get, and you're using regular arrays, you need a 1d array at least the total size of your 2d array, or you should just use an ArrayList. If you're set on using a primitive array, you could just add a counter that increases every time you find a new prime, and use that counter value as your index. This however would leave you with zeros on the back end of your array. If you want your index to correspond to the multi-dimensional array index, you multiply the row index by the number of members in the row, and then add the column index in order to get a 1d index as shown below. This would leave you with zeros inbetween elements in your array. Having zeros shouldn't necessarily be a bad thing since it isn't prime, but its still way easier in my mind to use an ArrayList.
int[][] nums2d = {{0,1,2},{3,4,5},{6,7,8}};
int[] nums1d = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int index = i * 3 + j;
nums1d[index] = nums2d[i][j];
}
}

Categories

Resources