bozhilov

ROITI Pyramid O(n^2)

Mar 14th, 2022 (edited)
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class Pyramid{
  4.  
  5.     public static void Build(int N){
  6.         int width = (int)(-1+Math.sqrt(1-(-4*2*N)))/2;
  7.         int number = 0;
  8.  
  9.         if((width*(width+1)/2)<N){
  10.             width++;
  11.         }
  12.  
  13.         StringBuilder spaces = new StringBuilder();
  14.         // concatenation O(n^2) and loop becomes O(n^3)
  15.  
  16.         for (int i = 1; i <= width; i++) {
  17.             spaces.setLength(0);
  18.             for (int j = 0; j < width-i; j++) {
  19.                 spaces.append(" ");
  20.             }
  21.             System.out.print(spaces);
  22.             for (int c = 0; c < i; c++) {
  23.                 if(number>=N)break;
  24.                 System.out.print(++number + " ");
  25.             }
  26.             System.out.print(spaces);
  27.            
  28.         System.out.println();
  29.         }
  30.     }
  31.  
  32.     public static void main(String[] args){
  33.         Scanner scanner = new Scanner(System.in);
  34.         System.out.println("Please, input N: ");
  35.         int N = scanner.nextInt();
  36.         Build(N);
  37.         scanner.close();
  38.     }
  39. }
Add Comment
Please, Sign In to add comment