Advertisement
Guest User

Untitled

a guest
Apr 5th, 2020
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.26 KB | None | 0 0
  1. import kotlinx.coroutines.*
  2. import java.util.concurrent.TimeUnit.SECONDS
  3.  
  4. /** Returns number of prime divisors of [n] */
  5. fun numberOfPrimeDivisors(n: Int): Int {
  6.     var i = 2
  7.     var currentN = n
  8.     var primeDivisors = 0
  9.     while (i * i <= currentN) {
  10.         if (currentN % i == 0) {
  11.             ++primeDivisors
  12.         }
  13.         while (currentN % i == 0) {
  14.             currentN /= i
  15.         }
  16.         ++i
  17.     }
  18.     if (currentN != 1) {
  19.         ++primeDivisors
  20.     }
  21.     return primeDivisors
  22. }
  23.  
  24. /**
  25.  * Sleeps for [n] seconds, after that gets char of the day, calling [charOfTheDay].
  26.  * If char of the day is not 'a', returns it, otherwise repeats
  27.  */
  28. suspend fun getSpecificCharOfTheDay(n: Int, charOfTheDay: () -> Char): Char {
  29.     while (true) {
  30.         delay(SECONDS.toMillis(n.toLong()))
  31.         val currentCharOfTheDay = charOfTheDay()
  32.         if (currentCharOfTheDay != 'a') {
  33.             return currentCharOfTheDay
  34.         }
  35.     }
  36. }
  37.  
  38. fun f(n: Int, charOfTheDay: () -> Char, callback: (Int, Char) -> Unit) {
  39.     GlobalScope.launch {
  40.         val currentCharOfTheDay = async { getSpecificCharOfTheDay(n, charOfTheDay) }
  41.         val primeDivisors = numberOfPrimeDivisors(n)
  42.         callback(primeDivisors, currentCharOfTheDay.await())
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement