Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercises week 1 #4

Open
ichko opened this issue Nov 8, 2020 · 4 comments
Open

Exercises week 1 #4

ichko opened this issue Nov 8, 2020 · 4 comments

Comments

@ichko
Copy link
Owner

ichko commented Nov 8, 2020

Тук може да споделяте решенията си на задачите от седмица 1. Самите задачи са дефинирани тук, а тук може да намерите нашите решения.

Публикувайте решенията като коментари в това issue или като линкове към ваши хранилища/gist.
Заградете кода на решението си по следния начин за да се highlight-не правилно (ако поствате коментар с кода тук):

```hs
-- solution
```
@Ivaylo-Valentinov
Copy link

even' n = mod n 2 == 0

factorial n = iter 1 1
  where
    iter i res
      | i > n = res
      | otherwise = iter (i + 1) (res * i)

pow x n = iter 1 1
  where
    iter i res
      | i > n = res
      | otherwise = iter (i + 1) (res * x)

fastPow _ 0 = 1
fastPow x n
  | even' n = evenPrev * evenPrev
  | otherwise = x * oddPrev * oddPrev
  where
    evenPrev = fastPow x (div n 2)
    oddPrev = fastPow x (div (n - 1) 2)

fib n = iter 1 1 3
  where
    iter cur prev i
      | i > n = cur
      | otherwise = iter (cur + prev) cur (i + 1)

isPrime 1 = False
isPrime n = iter 2
  where 
    iter cur
      | cur == n = True
      | mod n cur == 0 = False
      | otherwise = iter (cur + 1)

gcd' a b = iter 1 1
  where
    iter i result
      | i > a || i > b = result
      | (mod a i == 0) && (mod b i == 0) = iter (i + 1) i
      | otherwise = iter (i + 1) result

@ichko
Copy link
Owner Author

ichko commented Nov 16, 2020

@Ivaylo-Valentinov
Интересен алгоритъм за gcd, но работи само за положителни числа. Също така не съм сигурен за времевата му сложност но ми изглежда по-бавен от стандартният Евклидов алгоритъм.
Иначе нямам забележки към другите функции.

Добра работа! 😌

@dimitroffangel
Copy link
Contributor

even' n = n `mod` 2 == 0

factorialHelper currentResult counter counterMax = 
    if counter > counterMax
        then currentResult
        else factorialHelper (currentResult * counter) (counter + 1) counterMax
        
factorial n = factorialHelper 1 1 n

powHelper :: (Integral a1, Fractional a2, Integral a1) => a2 -> a2 -> a1 -> a2
powHelper currentResult base numberOfIterations =
    if numberOfIterations < 0 
        then powHelper currentResult (1/base) numberOfIterations
        else if numberOfIterations == 0
            then currentResult
            else if numberOfIterations == 1
                then (currentResult * base)
                else if numberOfIterations `mod` 2 == 0
                    then powHelper currentResult (base * base) (numberOfIterations `div` 2)
                    else powHelper (currentResult * base) (base * base) ((numberOfIterations - 1) `div` 2)

pow :: (Integral a1, Fractional a2, Integral a1) => a2 -> a1 -> a2
pow x n = powHelper 1 x n


fibonacciHelper a b iteration numberOfIterations = 
    if iteration > numberOfIterations
       then  a
        else fibonacciHelper (a + b) a (iteration + 1) numberOfIterations

fibonacci n = fibonacciHelper 1 1 3 n

isPrimeHelper :: (Integral t) => t -> t -> t -> Bool
isPrimeHelper n currentIteration numberOfIterations =
    if currentIteration * currentIteration > numberOfIterations
        then True
        else if n `mod` currentIteration == 0 
            then False
            else isPrimeHelper n (currentIteration + 1) numberOfIterations 


isPrime :: (Integral a) => a -> Bool
isPrime n = isPrimeHelper n 2 n

gcd' a 0 = a
gcd' 0 b = b
gcd' a b = 
    if b > a
        then gcd' a b
        else gcd' b (a `mod` b) 

@ichko
Copy link
Owner Author

ichko commented Dec 29, 2020

@dimitroffangel

  • Предпочитай гардове пред if then else.
  • Helper ф-иите е за предпочитане да се влагат в where клауза във ф-иите в които се използват.
  • Хубаво е да слагаш типова декларация на всеки израз.
  • Избягвай дълбоки влагания. Предпочитай да разделиш на няколко израза.

Благодаря че събмитна! ⭐

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants