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

huangapple go评论69阅读模式
英文:

Print a prime triangle in JAVA

问题

import java.util.Scanner;

public class PrimeTriangle {

    public static void main(String[] args) {
        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;
        }

        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));
            }
        }
    }
}
英文:

I am trying to print a triangle of 0s and 1s. You get a number N. If N was 5 the triangle should look like:

1
11
111
11101

I get wrong output with 27 for example

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. I have a problem because some lines ending with 0s are printed.

import 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&lt;=2; i++) {
nums[i]=true;
// 	System.out.print(nums[i]);
}
for (int i=4; i&lt;=n; i++) {
int m=i/2;
for (int j=2; j&lt;=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&lt;n; i++) {
if (nums[i]) {
digits[i]=&#39;1&#39;;
}
else {
digits[i]=&#39;0&#39;;
}
}
for (int i=0; i&lt;n; i++) {
if (digits[i]==1) {
System.out.println (new String (digits, 0, i+1));
/*for (int j=0; j&lt;i; j++) {
System.out.print(digits[i]);
}
System.out.println(); */ 
}
}
}
}

答案1

得分: 1

使用埃拉托斯特尼筛法(Sieve of Eratosthenes)构建一个由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));
}

测试

printPrimeTriangle(80);

输出

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
英文:

Use Sieve of Eratosthenes to build a char[] of 0's and 1's, then print all substrings ending in 1.

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

Test

printPrimeTriangle(80);

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

答案2

得分: 1

@kalina199
这是我的方法 - 我能够将它简化为只有一个循环 :)

包 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;
}

}


<details>
<summary>英文:</summary>
@kalina199
Here is my approach at it - I was able to reduce it to just one loop :)

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 &lt; 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 &lt;= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}

}


</details>
# 答案3
**得分**: 0
问题出在你的代码中:
===
1. 在循环内部,你将`isPrime`的值设为`true`。只有在通过循环的每个计数器将其除以后,发现它不能被循环计数器中的任何一个整除,才能确定这个数字是否是素数。因此,这应该在循环结束时才应该这样做。
2. 在声明部分中,`for (int i=4; i&lt;=n; i++)`,你已经将`i=4`声明为数字`5`,即如果`5`是素数,则将nums[4]设置为`true`,如果`5`不是素数,则设置为`false`。这意味着你想要测试`5`(而不是`4`)是否为素数。在你的代码中,你测试了`4`是否为素数。
下面是经过修正的代码:
```java
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;
}
}
// 如果j>m,说明循环没有因为`break`而终止
if (j > m) {
nums[i] = true;
}
}
// 为了测试而显示nums[]
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();
}
}
}
}
```
**一个示例运行:**
输入限制: 15
[true, true, true, false, true, false, true, false, false, false, true, false, true, false, false]
1
11
111
11101
1110101
11101010001
1110101000101
**附加说明:**
1. 我删除了一个不必要的变量`boolean isPrime`。数组`boolean nums[]`本身就足够了。我还打印了`nums[]`,这样你实际上可以看到这个数组中设置了什么值。
2. `boolean`变量只有两个值,`true`和`false`。因此,如果你在`if`中检查`boolean`变量的一个值,`else`部分就会变为另一个值的`true`。例如,在下面的代码中,`else if (nums[j]==true)`是不必要的,可以简单地写成`else`。
```java
if (nums[j]==false) {
continue;
} else if (nums[j]==true) {
//...
}
```
***更好的方法:***
===
1. 通过使用一个单独的函数来确定一个数是否为素数,可以使你的代码更加清晰。
2. 你不需要通过将数字除以每个小于等于其一半的整数来检查素数;你只需要将数字除以小于等于其平方根的整数。在[这里][1]了解更多信息。
3. 注意,通过使用三元运算符,我的代码看起来更加简洁。在[这里][2]了解更多关于三元运算符的信息。
```java
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;
}
}
```
**输出:**
1
11
111
11101
根据你的要求,即使`1`不是素数,也应该打印出`1`。另外,根据这个要求,我们不需要测试`0`或负整数是否为素数。因此,在方法`isPrime`中没有检查`0`、`1`或负数,以保持代码简洁,只与这个要求相关。
[1]: https://en.wikipedia.org/wiki/Primality_test
[2]: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
<details>
<summary>英文:</summary>
Problems in your code:
===
1. You have set the value of `isPrime` to `true` within the loop. 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&lt;=n; i++)`, you have declared `i=4` for the number `5` i.e. you want to set nums[4] to `true` if `5` is prime or `false` if `5` is not prime. It means that you want to test `5` (not `4`) for the primality. In your code, you have tested `4` for primality.
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(&quot;Enter the limit: &quot;);
int n = Integer.parseInt(input.nextLine());
boolean nums[] = new boolean[n];
for (int i = 0; i &lt;= 2; i++) {
nums[i] = true;
}
for (int i = 3; i &lt; n; i++) {
int num = i + 1, m = num / 2, j;
for (j = 2; j &lt;= m; j++) {
if (num % j == 0) {
nums[i] = false;
break;
}
}
// If j&gt;m, it means that the loop did not terminate because of `break`
if (j &gt; m) {
nums[i] = true;
}
}
// Display nums[] for testing
System.out.println(Arrays.toString(nums));
for (int j = 0; j &lt; n; j++) {
if (nums[j] == false) {
continue;
} else {
for (int i = 0; i &lt;= j; i++) {
if (nums[i] == true) {
System.out.print(&quot;1&quot;);
} else {
System.out.print(&quot;0&quot;);
}
}
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`. The array, `boolean nums[]` is sufficient in itself. I&#39;ve also printed `nums[]` so that you can actually see what values have been set in this array.
2. A `boolean` variable has only two values, `true` and `false`. Therefore, if you check one value of a `boolean` variable in `if`, the `else` part becomes `true` for the other value e.g. in the following code, `else if (nums[j]==true)` is unnecessary and it can simply be written as `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.
2. You do not need to check prime by dividing the number by each integer up to half of its value; you just need to divide the number by integers up to its square root. Check [this][1] to learn more about it.
3. Notice how my code looks cleaner by using the ternary operator. Check [this][2] 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 &lt;= N; i++) {
sb = new StringBuilder();
for (int j = 1; j &lt;= i; j++) {
sb.append(j == 1 || isPrime(j) ? 1 : 0);
}
if (sb.charAt(sb.length() - 1) != &#39;0&#39;) {
System.out.println(sb);
}
}
}
static boolean isPrime(int n) {
for (int i = 2; i &lt;= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
```
**Output:**
1
11
111
11101
As per your requirement, even though `1` is not a prime number, a `1` should be printed for it. Also, as per this requirement, we do not need to test `0` or a negative integer for primality. 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.
[1]: https://en.wikipedia.org/wiki/Primality_test
[2]: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
</details>
# 答案4
**得分**: 0
我创建了一个包含1和0的整数数组,并使用两个嵌套的for循环打印了三角形。外层循环是 i < n,内层循环是 j <= i。缺少了 = 导致输出错误。
<details>
<summary>英文:</summary>
I created an int array containing 1s and 0s and printed the triangle with two nested for loops. The outer loops is i&lt;n and the inner j&lt;=i. Missing the = was printing the wrong output
</details>

huangapple
  • 本文由 发表于 2020年5月3日 17:04:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/61571985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定