Question

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
Était-ce utile?

La solution

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 ();
}

Autres conseils

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();
   }

}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top