简体   繁体   English

在 JAVA 中打印一个素数三角形

[英]Print a prime triangle in JAVA

I am trying to print a triangle of 0s and 1s.我正在尝试打印一个由 0 和 1 组成的三角形。 You get a number N .你得到一个数字N If N was 5 the triangle should look like:如果N为 5,则三角形应如下所示:

1
11
111
11101

I get wrong output with 27 for example我弄错了 output 例如 27

1
11
111
11101
11101010
11101010001
11101010001010
11101010001010001
11101010001010001010

Lines ending with non-prime numbers are not printed, the prime numbers are printed as 1s, non-prime as 0s.不打印以非素数结尾的行,素数打印为 1,非素数打印为 0。 I have a problem because some lines ending with 0s are printed.我有一个问题,因为打印了一些以 0 结尾的行。

import java.util.Scanner;导入 java.util.Scanner;

public class PrimeTriangle {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner (System.in);
        int n = Integer.parseInt(input.nextLine());
        boolean isPrime=false;
        boolean nums[]=new boolean[n];

        for (int i=0; i<=2; i++) {
            nums[i]=true;
        //  System.out.print(nums[i]);
        }

        for (int i=4; i<=n; i++) {
            int m=i/2;
            for (int j=2; j<=m; j++) {
                if (i%j==0) {
                isPrime=false;
                break;
                }
                else {
                isPrime=true;
                }

            }
            nums[i-1]=isPrime;

        }
char[] digits = new char[n];
        for (int i=0; i<n; i++) {
            if (nums[i]) {
                digits[i]='1';
            }
            else {
                digits[i]='0';
            }
        }
for (int i=0; i<n; i++) {
            if (digits[i]==1) {
                System.out.println (new String (digits, 0, i+1));
                /*for (int j=0; j<i; j++) {
                    System.out.print(digits[i]);
                }
                System.out.println(); */ 
            }
        }

    }

}

@kalina199 Here is my approach at it - I was able to reduce it to just one loop:) @kalina199 这是我的方法 - 我能够将它减少到一个循环:)

package bg.Cholakov;

import java.util.Scanner;

public class PrimeTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        int[] array = new int[n];
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0, j = 1; i < n; i++, j++) {
            array[i] = j;
            if (isPrime(array[i])) {
                array[i] = 1;
                stringBuilder.append(String.valueOf(array[i]));
                System.out.println(stringBuilder);

            } else {
                array[i] = 0;
                stringBuilder.append(String.valueOf(array[i]));

            }
        }
    }

    static boolean isPrime(int number) {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Problems in your code:您的代码中的问题:

  1. You have set the value of isPrime to true within the loop.您已在循环内将isPrime的值设置为true You can not tell if the number is prime until you have divided it with each counter of the loop and found that it is not divisible by any of the loop counters.在你将它与循环的每个计数器相除并发现它不能被任何循环计数器整除之前,你无法判断该数字是否为素数。 Therefore, it should be done only when the loop is finished.因此,只有在循环结束时才应该这样做。
  2. In the declaration, for (int i=4; i<=n; i++) , you have declared i=4 for the number 5 ie you want to set nums[4] to true if 5 is prime or false if 5 is not prime.在声明中, for (int i=4; i<=n; i++) ,您已经为数字5声明了i=4 ,也就是说,如果5是素数,您希望将 nums[4] 设置为true ,如果5不是,则设置为false主要。 It means that you want to test 5 (not 4 ) for the primality.这意味着您要测试5 (而不是4 )的素数。 In your code, you have tested 4 for primality.在您的代码中,您已经测试了4的素数。

Given below is the corrected code:下面给出的是更正后的代码:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the limit: ");
        int n = Integer.parseInt(input.nextLine());
        boolean nums[] = new boolean[n];

        for (int i = 0; i <= 2; i++) {
            nums[i] = true;
        }

        for (int i = 3; i < n; i++) {
            int num = i + 1, m = num / 2, j;
            for (j = 2; j <= m; j++) {
                if (num % j == 0) {
                    nums[i] = false;
                    break;
                }
            }

            // If j>m, it means that the loop did not terminate because of `break`
            if (j > m) {
                nums[i] = true;
            }
        }

        // Display nums[] for testing
        System.out.println(Arrays.toString(nums));

        for (int j = 0; j < n; j++) {
            if (nums[j] == false) {
                continue;
            } else {
                for (int i = 0; i <= j; i++) {
                    if (nums[i] == true) {
                        System.out.print("1");
                    } else {
                        System.out.print("0");
                    }
                }
                System.out.println();
            }
        }
    }
}

A sample run:示例运行:

Enter the limit: 15
[true, true, true, false, true, false, true, false, false, false, true, false, true, false, false]
1
11
111
11101
1110101
11101010001
1110101000101

Additional notes:补充说明:

  1. I have removed an unnecessary variable, boolean isPrime .我删除了一个不必要的变量boolean isPrime The array, boolean nums[] is sufficient in itself.数组boolean nums[]本身就足够了。 I've also printed nums[] so that you can actually see what values have been set in this array.我还打印了nums[]以便您可以实际看到在这个数组中设置了哪些值。
  2. A boolean variable has only two values, true and false . boolean变量只有两个值, truefalse Therefore, if you check one value of a boolean variable in if , the else part becomes true for the other value eg in the following code, else if (nums[j]==true) is unnecessary and it can simply be written as else .因此,如果您在if中检查boolean变量的一个值,则else部分对另一个值变为true ,例如在以下代码中, else if (nums[j]==true)是不必要的,它可以简单地写成else .
if (nums[j]==false) {
    continue;
} else if (nums[j]==true) {
    //...
}

A better approach:更好的方法:

  1. You can make your code much cleaner by using a separate function to determine if a number is prime.您可以通过使用单独的 function 来确定数字是否为素数,从而使您的代码更加简洁。
  2. You do not need to check prime by dividing the number by each integer up to half of its value;您不需要通过将数字除以每个 integer 直到其值的一半来检查素数; you just need to divide the number by integers up to its square root.您只需要将数字除以整数,直到其平方根。 Check this to learn more about it.检查以了解更多信息。
  3. Notice how my code looks cleaner by using the ternary operator.注意使用三元运算符我的代码看起来更干净。 Check this to learn more about the ternary operator.检查以了解有关三元运算符的更多信息。
public class Main {
    public static void main(String[] args) {
        final int N = 5;
        StringBuilder sb;
        for (int i = 1; i <= N; i++) {
            sb = new StringBuilder();
            for (int j = 1; j <= i; j++) {
                sb.append(j == 1 || isPrime(j) ? 1 : 0);
            }
            if (sb.charAt(sb.length() - 1) != '0') {
                System.out.println(sb);
            }
        }
    }

    static boolean isPrime(int n) {
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Output: Output:

1
11
111
11101

As per your requirement, even though 1 is not a prime number, a 1 should be printed for it.根据您的要求,即使1不是质数,也应为其打印1 Also, as per this requirement, we do not need to test 0 or a negative integer for primality.此外,根据此要求,我们不需要测试0或负 integer 的素数。 Therefore, I have not put any check for 0 , or 1 or a negative number in the method, isPrime to keep it clean and just relevant for this requirement.因此,我没有在方法isPrime中对01或负数进行任何检查,以保持其干净且仅与此要求相关。

Use Sieve of Eratosthenes to build a char[] of 0's and 1's, then print all substrings ending in 1.使用Eratosthenes 的 Sieve构建一个 0 和 1 的char[] ,然后打印所有以 1 结尾的子字符串。

static void printPrimeTriangle(int n) {
    char[] primes = new char[n];
    Arrays.fill(primes, '1');
    for (int sqrt = (int) Math.sqrt(n) + 1, i = 1; i < sqrt; i++)
        if (primes[i] == '1')
            for (int prime = i + 1, j = prime * 2 - 1; j < n; j += prime)
                primes[j] = '0';
    for (int i = 0; i < n; i++)
        if (primes[i] == '1')
            System.out.println(new String(primes, 0, i + 1));
}

Test测试

printPrimeTriangle(80);

Output Output

1
11
111
11101
1110101
11101010001
1110101000101
11101010001010001
1110101000101000101
11101010001010001010001
11101010001010001010001000001
1110101000101000101000100000101
1110101000101000101000100000101000001
11101010001010001010001000001010000010001
1110101000101000101000100000101000001000101
11101010001010001010001000001010000010001010001
11101010001010001010001000001010000010001010001000001
11101010001010001010001000001010000010001010001000001000001
1110101000101000101000100000101000001000101000100000100000101
1110101000101000101000100000101000001000101000100000100000101000001
11101010001010001010001000001010000010001010001000001000001010000010001
1110101000101000101000100000101000001000101000100000100000101000001000101
1110101000101000101000100000101000001000101000100000100000101000001000101000001

....:....1....:....2....:....3....:....4....:....5....:....6....:....7....:....8

I created an int array containing 1s and 0s and printed the triangle with two nested for loops.我创建了一个包含 1 和 0 的 int 数组,并用两个嵌套的 for 循环打印了三角形。 The outer loops is i外环是 i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM