Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation with an algorithm

Tags:

algorithm

math

Sorry I couldn't think of a good title.

I am working on a ICT related exercise and come across this:

Calculate alg a(n) and alg b(n) for n = 1,2,3,4 and 5

(a)
    alg_a(n):result
    if n > 1 then
    return(alg_a(n−1)+alg_a(n−1))
    else return(1)

(b)
    alg_b(n):result
    if n > 1 then
    return(2 · alg_b(n−1))
    else return(1)

At first, what does the code at line 1 do (alg_a(n):result)?

A: The question asks me to calculate alg a(n) so lets say I insert 1, if n > 1 --> no --> return 1. But what happens when I insert n = 2.

Any help is appreciated,

thanks!

like image 947
Jef Avatar asked Aug 16 '26 14:08

Jef


2 Answers

algorithm alg_a(n) calculates 2^(n-1) and alg_b(n) does the same thing.
Theese are recursive functions. For example for 4 alg_a returns:
alg_a(4)=
alg_a(3) + alg_a(3) =
alg_a(2) + alg_a(2) + alg_a(2) + alg_a(2) =
alg_a(1) + alg_a(1) + alg_a(1) + alg_a(1) + alg_a(1) + alg_a(1) + alg_a(1) + alg_a(1) = 8

like image 195
shift66 Avatar answered Aug 20 '26 07:08

shift66


This isn't code, it's some form of pseudo-code. The work "result" just means that what follows is the result of the function. So, alg_a(1) gives you the result of 1, whereas alg_a(2) gives you the result (alg_a(1) + alg_a(1)), i.e. 2. Continue to get your other answers.

The question in this case isn't asking for anything more complicated than the numeric answers.

like image 45
David M Avatar answered Aug 20 '26 06:08

David M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!