Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 如何知道循环中的迭代次数_Loops_Iterator - Fatal编程技术网

Loops 如何知道循环中的迭代次数

Loops 如何知道循环中的迭代次数,loops,iterator,Loops,Iterator,这个循环将运行多少次,持续n个月?我假设它将包含一个日志,因为我们每次都除以2。我想是logn,但我不确定。谢谢 考虑到您只想检查它运行了多少次,您可以执行以下操作,当然您的代码不会运行: 最后将计数器打印为 int counter = 0; static void bar(int n) { for (int i = n!; i>=1; i=i/2){ counter++; } } 另外,你需要做的不是n! 可能是 System.out.println(

这个循环将运行多少次,持续n个月?我假设它将包含一个日志,因为我们每次都除以2。我想是logn,但我不确定。谢谢

考虑到您只想检查它运行了多少次,您可以执行以下操作,当然您的代码不会运行:

最后将计数器打印为

int counter = 0;
    static void bar(int n) {
       for (int i = n!; i>=1; i=i/2){
counter++;
}
      }
另外,你需要做的不是n! 可能是

System.out.println(counter);//this will display how many iterations were achieved
并创建如下函数:

static void bar(int n) {
   for (int i = factorialOf(n); i>=1; i=i/2);
  }

什么是lgn!?正如所指出的,这是由于每次i/2的变化。这段代码是否运行?@Nabin没有给出。没有后缀一元!运算符。不,我只是想知道它实际运行代码的次数。它应该是Ologn!=在长筒袜上!所以有了helper函数,大O就是n*logn!对吧?奥洛恩!=登录
static void bar(int n) {
   for (int i = factorialOf(n); i>=1; i=i/2);
  }
public int factorialOf(int n){//assuming your return isn't huge else use long or double
//your logic goes here
}