0

I'm trying to create a prime factorization function (recursively), my issue is that the while loop ends after calling the function itself.

Code:

primeFactors(){
    if isPrime $1; then
        echo "$1"
    else
        i=2
        sqrtnum=`echo "sqrt($1)"|bc`
        while [ $i -lt $sqrtnum ]
        do
            echo "I: $i sqr: $sqrtnum"
            j=$(($1%i))
            if isPrime $i && [ $j -eq 0 ]
            then
                echo "$i"
                num=$(($1/$i))
                primeFactors $num
            fi
            let i++
        done
    fi
}

The output is this

I: 2 sqr: 10
2
I: 2 sqr: 7
2
I: 2 sqr: 5
I: 3 sqr 5
I: 4 sqr 5

1 Answer 1

3

Your variables are global.

Later function calls override earlier assignments.

You need to make the variables local.

Add set -x to the top of your script to see what is actually being run.

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

Comments

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.