以颠倒的直角形式打印奇数

时间:2014-10-06 04:16:05

标签: java loops

我试图拿一个号码打印出奇怪的数字:

    if i take 5 as a number it should give this: 

    1 3 5
    3 5
    5

   and if i take 9 it should do the same thing:

  1 3 5 7 9
  3 5 7 9
  5 7 9
  7 9
  9

这是我到目前为止所遇到的情况。我不能在3之后打印5并且以3为三角形结束它:

public class first{
    static void afficher(int a){
    for(int i=1;i<=a;i++){
        if(i%2!=0){
            System.out.printf("%d",i);
        }
    }
    System.out.println();

    for(int j=3;j<=a-2;j++){
        if(j%2!=0){
            System.out.printf("%d",j);
        }
    }
}




     public static void main(String[]args){
        afficher(5);


    }

}

打印:

1 3 5
3

3 个答案:

答案 0 :(得分:1)

如果打印曲面(因此为2d),则可以预期该算法以 O(n ^ 2)时间复杂度运行。因此,两个嵌套for s:

public class first{
    static void afficher(int a){
        for(int i = 1; i <= a; i += 2) {
            for(int j = i; j <= a; j += 2){
                System.out.print(j);
                System.out.print(' ');
            }
            System.out.println();
        }
    }
}

可以通过不检查if数字是奇数,但采取2的步骤来优化算法。

请参阅demo

答案 1 :(得分:0)

The reason it is printing as follows because:

1 3 5 -> your i loop runs here (from 1 to 5)
3     -> your j loop runs here (from 3 to (less than OR equal to 5))

So i suggest the following:

1. Use 2 nested loops (for universal values):
 i running from 1 to the input number increasing by 2
 j running from i to the input number increasing by 2 also ending with line change'/n'  

2. Keep a check whether the input number is odd or not.

Hope that helps !

答案 2 :(得分:0)

您必须使用嵌套for循环来解决此问题。完成以下代码,

public class OddNumberLoop {

 public static void main(String[] args) {

    Scanner inpupt = new Scanner(System.in);

    System.out.print("Input the starting number : ");
    int start = inpupt.nextInt();
    for(int i = 1 ; i <= start; i += 2){
        for(int x = i; x <= start; x += 2) System.out.print(x+ " ");
        System.out.println();
    }

 }

}

祝你好运!!!