获取科特林的数字因子 [英] Get Factors of Numbers in Kotlin

查看:105
本文介绍了获取科特林的数字因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

科特林(Kotlin)的新手,如何找到数字的因素?

Brand new to Kotlin, how can I find the factors of a number?

例如24应该给出1、2、3、4、6、8、12、24?

For example 24 should give 1, 2, 3, 4, 6, 8, 12, 24?

我知道如何使用列表理解功能来执行此python,但不确定如何在Kotlin中正确执行操作.

I know how to do this python with a list comprehension but not sure how to do it properly in Kotlin.

推荐答案

不确定在Kotlin中如何进行列表理解",但可以使用下面的factorsOfNumbers之类的函数:

Not sure how you could do a "list comprehension" in Kotlin but instead you can use a function like factorsOfNumbers below:

fun factorsOfNumber(num: Int) : MutableList<Int> {
  val factors = mutableListOf<Int>()
  if (num < 1) 
    return factors
  (1..num / 2)
    .filter { num % it == 0 }
    .forEach { factors.add(it) }
  factors.add(num)
  return factors
}

fun main(args: Array<String>) {
  val number = 24
  println("The factors of $number are: " + factorsOfNumber(number).joinToString())
}

输出:

The factors of 24 are: 1, 2, 3, 4, 6, 8, 12, 24

以下是了解其工作原理的相关文档:

Relevant documentation to understand how it works is below:

  • Collections: List, Set, Map (MutableList stuff)
  • Ranges (The (1..num / 2) part)
  • Kotlin Idioms (Everything else)

这篇关于获取科特林的数字因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆