Editorial for Prime Triangle


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.
by: doncho

Sample solutions:

Video in BG

JavaScript

let line = '1';
print(line);

for (let number = 2; number < n + 1; number += 1) {
    let isPrime = true;
    const maxDivisor = Math.sqrt(number);
    for (let divisor = 2; divisor <= maxDivisor; divisor += 1) {
        if (number % divisor === 0) {
            isPrime = false;
            break;
        }
    }

    if (isPrime) {
        line += '1';
        print(line);
    } else {
        line += '0';
    }
}

Java

import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();

    String row = "";

    for (int number = 1; number <= n; number++) {
      int maxDivider = (int) Math.sqrt(number);
      boolean isPrime = true;

      for (int divider = 2; divider <= maxDivider; divider++) {
        if (number % divider == 0) {
          isPrime = false;
        }
      }

      if (isPrime) {
        row += "1";
        System.out.println(row);
      } else {
        row += "0";
      }
    }
  }
}

Comments


  • 0
    assendk
     commented on July 25, 2018

    PHP 7+

    <?php
    $n = fgets(STDIN);
    settype($n, "int");
    $row = "";
    for ($i = 1; $i < $n + 1; $i++ ){
        $isPrime = true;
        $maxD = (int) sqrt($i);
        for ($j = 2; $j <= $maxD; $j++) {
            if ($i % $j == 0) {
                $isPrime = false;
                break;
            }
        }
        if($isPrime){
            $row .= "1";
            echo $row.PHP_EOL;
        } else {
            $row .= "0";
        }
    }