使用for循环打印素数的三角形

时间:2014-05-13 15:54:53

标签: java loops primes

我正在尝试制作素数的三角形..行数将由用户定义 例如,如果用户给出" 4"作为行数,程序应该显示一个包含4行

的素数三角形
input :4

output : 

2
3 5
7 11 13
17 19 23 29

3 个答案:

答案 0 :(得分:0)

这是两个任务:获取素数列表(或类似nextPrime(int)之类的东西)并得到三角形,两者都非常简单。

首先,您可以查看Next Prime number Java only working with certain numbers

对于第二个实现,只需执行以下操作:

for (int i = 1; i <= n; ++i) {
    for (int j = 0; j < i; ++j) {
        nextPrime = ...
        System.out.print (nextPrime + " ");
    }
    System.out.println ();
}

答案 1 :(得分:0)

假设你已经有了素数(足够数量)。

int[] primes = ...;

然后对于N个字符串,create array是StringBuilders并用你的数字填充它们:

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

然后你可以打印它们

for(StringBuilder sb : builders) 
    System.out.println(sb);

答案 2 :(得分:0)

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

}
}