Problem with unresolved identifier. Please help!

Hi, I just started coding and ran into this problem with which trying to write code to print out prime numbers up to n. There is an unresolved identifier error on line 17 with "return number" but I checked it many times and made sure I didn't have typos or out of place braces or parenthesis. What am I doing wrong?

Re-indent your code and you'll see that the problematic number is outside for loop.

var divisibleCounter = 0

func printNumbers(upTo n: Int) -> Int {
    for number in 2...n {
        let endNumber = n
        while (number % 1 == 0 && endNumber % number == 0) {
            divisibleCounter += 1
            if divisibleCounter != 1 {
                divisibleCounter = 0
                break
            }
            print("\(number) is print")
        }
    }
    return number
}

Since number originally is declared as part of for loop, it doesn't have any meaning outside of the said loop.

If you want to return the last value of number before you get out of the loop, try returning if when you break out of it.

var divisibleCounter = 0

func printNumbers(upTo n: Int) -> Int {
    for number in 2...n {
        // You can use `number` here
        let endNumber = n
        while (number % 1 == 0 && endNumber % number == 0) {
            divisibleCounter += 1
            if divisibleCounter != 1 {
                divisibleCounter = 0
                return number // Here
            }
            print("\(number) is print")
        }
    }
    // `number` is part of for loop, the for loop has ended, you can no longer use `number here`
    return n // If we ends the loop normally, `number` should have value of `n`
}

PS: Your algorithm doesn't print prime number up to n. :wink:

1 Like

Thanks, I'm still working on it. I re-indented it and saw my error, but I also realized that I didn't really need to return a value in this problem.

1 Like
Terms of Service

Privacy Policy

Cookie Policy