I have written a small program to develop logarithmic code and I have taken 3 variables, x
, y
and p
, where x
is base, y
is log value and p
is default value (power of 'x
'). Now I am not getting error when I executed it but it didn't display any answer on terminal. It will be handy when someone provide solution to it.
algo1 <- function(x, y) {
p <- 1
if (x ^ p == y) {
print(p)
} else {
p <- p + 1
}
algo1(3, 81)
There are a few issues I can see here.
Assigning p
inside the function, while it seems the function has to be recursive.
OR, considering for some reason you want to increment p
within the else
condition and still not do anything with the incremented value, not returning anything here.
If I may, I would change the function to something like:
algo1 <- function(x,y,p = 1) {
if (x ^ p == y) {
print(p)
} else {
p = p + 1
algo1(x,y,p)
}
}
which returns the value of p
for which x^p ==y
> algo1(3,81)
[1] 4
OR, you can also use:
round(y ^ (1.0/x))
p.s. maybe include a check and exit conditions for x^p > y
?