Kotlin Program to Display Factors of Given Number

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Write a Kotlin Program to Display Factors of Given Number.

For example,

Input
12

Output
1 2 3 4 6 12
Input
50

Output
1 2 5 10 25 50
Input
6

Output
1 2 3 6

1. Program to Display Factors of Number

Pseudo Algorithm
  • For any number n, 1 and n are two factors of n.
  • Then, run a loop from 2 to n/2 and check if n is divisible for any value between 2 and n/2.
  • If yes, then, that value is factor of n.

Sourcecode –

fun main() {
    val read = Scanner(System.`in`)

    println("Enter n:")
    val n = read.nextInt()

    println("Factors of $n:")

    print("1 ")

    for(i in 2..(n/2)) {
        if((n%i) == 0) {
            print("$i ")
        }
    }

    println("$n")
}

When you run the program, output will be –

Enter n:
100
Factors of 100:
1 2 4 5 10 20 25 50 100
Explanation:

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.

Then,

  • value read by nextInt() stored in variable n.
  • Print 1 as 1 is factor of all numbers
  • Then, run a loop from 2 to n/2. This is because all factors (except 1 and number itself) lies between 2 to n/2 only.
  • Print value between 2 to n/2 if it divides n.
  • After for loop is complete, print n. This is because any number is always a factor of that number itself.
  • That’s it.

Thus, we went through Kotlin Program to display factors of a given number.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners