Here is a piece of c++ code, trying to understand and find out how many times the function is called.
#include <iostream>
int func(int j){
if (j <= 0) return -1;
if (j == 1) return 1;
return func(j/2) + func(j-4);
}
int main(){
func(4);
}
func(4)
will be evaluated as func(2)+func(0)
. func(2)
will in turn be evaluated as func(1)+func(-2)
. In total, you will call func(4)
, func(2)
, func(1)
, func(-2)
, func(0)
( 5 times). The resulting expression will be func(1)+func(-2)+func(0)
, which is 1+(-1)+(-1)
or just -1
.
An easy way to check that would be adding std::cout << “something\n”;
in the first line of function definition.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.