Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class Pyramid{
- public static void Build(int N){
- int width = (int)(-1+Math.sqrt(1-(-4*2*N)))/2;
- int number = 0;
- if((width*(width+1)/2)<N){
- width++;
- }
- StringBuilder spaces = new StringBuilder();
- // concatenation O(n^2) and loop becomes O(n^3)
- for (int i = 1; i <= width; i++) {
- spaces.setLength(0);
- for (int j = 0; j < width-i; j++) {
- spaces.append(" ");
- }
- System.out.print(spaces);
- for (int c = 0; c < i; c++) {
- if(number>=N)break;
- System.out.print(++number + " ");
- }
- System.out.print(spaces);
- System.out.println();
- }
- }
- public static void main(String[] args){
- Scanner scanner = new Scanner(System.in);
- System.out.println("Please, input N: ");
- int N = scanner.nextInt();
- Build(N);
- scanner.close();
- }
- }
Add Comment
Please, Sign In to add comment