Q:

Kotlin program to print all prime factors of given number

belongs to collection: Kotlin Basic Programs

0

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

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

Example:

    Input:
    50

    Output:
    2, 5

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print all prime factors of given number in Kotlin

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]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to check Armstrong number... >>
<< Kotlin program to reverse a number...