当前位置:网站首页>Getting Started with Kotlin Algorithms Calculating Prime Factors

Getting Started with Kotlin Algorithms Calculating Prime Factors

2022-08-11 08:12:00 Yi Pangzhou

/* 每个非素数(合数)都可以写成几个素数(也可称为质数)相乘的形式,这几个素数就都叫做这个合数的质因数. 比如,6可以被分解为2x3,而24可以被分解为2x2x2x3. 现在,你的程序要读入一个[2,100000]范围内的整数,然后输出它的质因数分解式;当读到的就是素数时,输出它本身 */ class QualityFactor {

    /**  * Because no matter how you calculate it, it can pass because of non-prime numbers1·9is calculated by multiplication, so except1和2Just go ahead and see if it can be2-9整除就可以  * This statement is calculated by extracting the least common factor  * Of course an important problem to avoid is when it's a single digit number1 、 2 、 3 、 5 、7的时候直接返回  * The advantage of this calculation is that it avoids traditional recursive slaves1到nThe repeated calculation is more efficient to calculate the prime number in the face of data with more than one thousand digits  * Excessive use of this algorithm is also avoided(Redundant repetitive calculations)的:  * 判断素数的方法:用一个数分别去除2到sqrt(这个数的平方根),如果能被整除, 则表明此数不是素数,Conversely, the prime number algorithm is faster  * The redundancy of repeated calculation is avoided  */  fun isPrimeNumber(divisor: Int, number: Int): Boolean {
        if (number % divisor == 0)
            return false  else if (number == 1 || number == 2 || number == 3 || number == 5 || number == 7
                || number == 11 || number == 13 || number == 17 || number == 19)
            return true  else if (number <= 20)
            return false  else if (divisor == 9) {
            return isPrimeNumber(11, divisor)
        } else if (divisor > 9) {
            return if (divisor < Math.sqrt(number.toDouble())) {
                isPrimeNumber(divisor + 1, number)
            } else if (divisor.toDouble() == Math.sqrt(number.toDouble()))
                false  else  true  }
        return isPrimeNumber(divisor + 1, number)
    }

    fun getQualityFactor(number: Int) {
        var number = number
        var out = number.toString() + "="  if (isPrimeNumber(2, number))
            out = out + number
        else {
            while (number != 1) {
                for (j in 2..number) {
                    /*如果每一次Number都能整除j则让Number/=j*/  if (number % j == 0) {
                        number /= j
                        /*After the division is completed, it is determined whether it is a prime number, so as to avoid a relatively large prime number remaining at the end and then need to perform repeated calculations*/  if (number != 1) {
                            out += j.toString() + "x"  if (isPrimeNumber(2, number)) {
                                out += number
                                number = 1
                            }
                        } else  out += j

                        break  }
                }
            }
        }
        println(out)
    }
}
原网站

版权声明
本文为[Yi Pangzhou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110801037400.html