1

I have been trying to solve the problem below in multiple ways (recursively, with the Go-version of do while loop, and with a for loop). But each one of them goes to an infinite loop. I tried using the same solution in JavaScript, and it works perfectly fine. Can someone please help me understand why the solution below is not working/going on an infinite loop?

// Write a function that takes in a number and returns the next number that is divisible by 7
package main                   

func solution9(num int) int {  

        var done bool = false  
        var result int = 0     

        for i := 1; done != true; i++ { 
                if (num + i % 7 == 0) {         
                        result = num + i                
                        done = true                     
                }              
        }                      

        return result          
}

1 Answer 1

10

Your issue is operator precedence. The % operator has a higher precedence than the + operator, so if your num is, say, 10, your test is functionally:

10 + (0 % 7) == 0 => false (10)
10 + (1 % 7) == 0 => false (11)
10 + (2 % 7) == 0 => false (12)

etc.

Obviously, for any num > 0, you'll never satisfy the condition. Change your test to (num+i)%7 == 0 and you should find it works as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

You're an angel. Lol. Thank you Chris!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.