Kotlin program to find factors of a number

Kotlin | Factors of a number: Here, we are going to learn how to find the factors of a given number in Kotlin programming language? Submitted by IncludeHelp, on April 25, 2020

What are the factors?

Factors of a number are those numbers you multiply them to get the number. For example: If a number is 6, it's factors will be 2 and 3, if we multiply them, then it will be the number again: 2x3=6.

Kotlin - Find factors of a number

Given a number, we have to find its all factors.

Example:

Input:
number = 6

Output:
2, 3

Program to find factors of a number in Kotlin

package com.includehelp.basic

import java.util.*

//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val scanner = Scanner(System.`in`)

    //input integer number
    println("Enter Number  : ")
    val number: Int = scanner.nextInt()

    //Declare Mutable List to hold factors
    val list: MutableList<Int> = ArrayList()

    //Find the factor of using loop
    for(i in 1..number){
        if(number%i==0){
            list.add(i)
        }
    }

    //print factors
    println("Factors of $number are $list")
}

Output

Run 1:
Enter Number  :
240
Factors of 240 are [1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 40, 48, 60, 80, 120, 240]

-------
Run 2:
Enter Number  :
500
Factors of 500 are [1, 2, 4, 5, 10, 20, 25, 50, 100, 125, 250, 500]
-------
Run 3:
Enter Number  :
179
Factors of 179 are [1, 179]

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.