Kotlin program to print all prime factors of given number

Kotlin | printing prime factors: Here, we are going to learn how to print all prime factors of a given number in Kotlin? Submitted by IncludeHelp, on April 17, 2020

Prime factors are factors of a number which are prime numbers.

Problem statement

Given an integer number, we have to print it's all prime factors.

Example:

Input:
50

Output:
2, 5

Program to print all prime factors of given number in Kotlin

In the below program, we are creating a Kotlin program to print all prime factors of the given number.

package com.includehelp.basic

import java.util.*

/**
 * Function to find prime factor for supplied number
 * @param number
 * @return
 */
fun getPrimeFactors(number: Long): String {
    var number = number
    //set not Allowed Duplicate element
    val setPrimeFactors: MutableSet<Int> = HashSet() 
    var i = 2
    while (i <= number) {
        if (number % i == 0L) {
            // Add prime factor in Hash Set
            setPrimeFactors.add(i)               
            number /= i
            i--
        }
        i++
    }
    return setPrimeFactors.toString()
}

//Main Function entry Point of Program
fun main(args: Array<String>) {
    val sc = Scanner(System.`in`)
    
    println("Enter Number  : ")
    val number: Int = sc.nextInt()       // Input Number
    
    //Print Primary Factor
    println("Prime Factors of  $number  is :  ${getPrimeFactors(number.toLong())} ") 
}

Output

Run 1:
Enter Number  :
50
Prime Factors of  50  is :  [2, 5]
-------
Run 2:
Enter Number  :
345345
Prime Factors of  345345  is :  [3, 5, 7, 23, 11, 13]

Comments and Discussions!

Load comments ↻





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