-1

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)
Phil
  • 4,344
  • 2
  • 23
  • 33
sk jainmiah
  • 53
  • 2
  • 2
  • 10

2 Answers2

1

First, there's a problem with your code where you don't close the function (i.e. you're missing the final }) and you're mixing <- and = assignments (stick with one):

algo1 <- function(x, y) {
  p <- 1
  if (x ^ p == y) {
    print(p)
  } else {
    p <- p + 1
  }
}

After solving this, you're not getting a returned value because you're not return()ing anything. To return, just place the variable in the code:

algo1 <- function(x, y) {
  p <- 1
  if (x ^ p == y) {
    p
  } else {
    p <- p + 1
    p
  }
}

The function now returns:

algo1(3, 81)
# [1] 2
Phil
  • 4,344
  • 2
  • 23
  • 33
  • Would this not return the value `2` for all non-equal values of `x` and `y`? Agreed, OP has not mentioned clearly what he wants, still... – Aramis7d May 26 '17 at 10:41
  • Possibly, I didn't look at the logic, just why it wasn't returning. – Phil May 26 '17 at 10:42
  • Thanks for responding and providing solution to my question even though i wasn't clear with my question. Hope next time i will clearly mention it – sk jainmiah May 27 '17 at 09:39
0

There are a few issues I can see here.

  1. Assigning p inside the function, while it seems the function has to be recursive.

  2. 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?

Aramis7d
  • 2,444
  • 19
  • 25
  • Thanks for solving this problem, why #algo1(x,y,p) should be added? and how can i be in touch with you as a new person to R - programming. – sk jainmiah May 27 '17 at 09:37
  • if i pass values algo1(5,0.0016) it shows infinite solution – sk jainmiah May 27 '17 at 09:49
  • Initialising `p` is not specific to R language, please read [here](https://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/recursion2.html) and [here for R examples](https://www.programiz.com/r-programming/recursion). It goes to infinite loops as we initialise `p = 1` and go up, and does not include a termination condition for such cases. What output do you expect for such an input? – Aramis7d May 29 '17 at 05:20