Finding Unknown variable "x" that satisfies two mod conditions

190 Views Asked by At

I was wondering how to find the smallest integer "x," that satisfies two mod conditions.

    x%%7 == 1
    x%%10 == 2

I have attempted to use for/while loops within a function, like so with no such luck:

  min.integer <- function(x) {
    y = c(1:500000)
    for (i in y) {
      if (x%%10 == 2) {
        print(x)
      } else {
        break
      }     
    }
  }

Is this the best way to approach this problem? Thank you!

2

There are 2 best solutions below

0
Onyambu On BEST ANSWER

A simple while loop

m=n=0
x=1
while(!(m==1&n==2)){
  x=x+1
  m=x%%7
  n=x%%10
}
x
22
0
Georgery On

This might help:

twoModsSatisfied <- function(
    mod1
    , equals1
    , mod2
    , equals2
    , howMany # how many different values do you want to try
){
    x <- (0:howMany) * mod1 # all these values will satify the 1st condition
    x[which((x + equals1) %% mod2 == equals2)][1] + equals1
}

twoModsSatisfied(
    7
    , 1
    , 10
    , 2
    , 100
)

The [1] makes sure you only get the first value that satisfies the condition. 0:howMany makes sure you get the correct result for twoModsSatisfied(7,2,10,2,100). The function doesn't check if the request is impossible (e.g. twoModsSatisfied(7,8,10,2,100)), but this can be done easily as well using an ifstatement.