0

Quick- Alternate to recursive code

what could be alternate to this code? long pp (int b, int a) { if (a!=1) return (b*pp (b,a-1)); else return b; }

18th Feb 2018, 4:48 PM
Salar Khan
Salar Khan - avatar
3 Respuestas
+ 9
long pp(int b, int a) { long res = b; for (; a != 1; a--) res *= b; return res; }
18th Feb 2018, 4:58 PM
Hatsy Rei
Hatsy Rei - avatar
+ 6
I believe the aim of the function is to raise b to the power of a. pp(2, 2) returns 4 pp(3, 3) returns 27 etc. Knowing the logic behind the code makes it easy to manifest a non-recursive version of it. That said, it doesn't consider negative values and case 0.
18th Feb 2018, 5:27 PM
Hatsy Rei
Hatsy Rei - avatar
0
can you explain it a bit @Hatsy?
18th Feb 2018, 5:00 PM
Salar Khan
Salar Khan - avatar