算法题

13 阅读1分钟
/**
 * 判断一个数是否是素数
 * @param {*} num 
 * @returns 
 */
export const isPrimeNumber = (num) => {
    if ([1, 2, 3].includes(num)) return true;
    let remainder = 2;
    let has = false
    for(let i = 2; i < num; i++){
        if (num % remainder !== 0 && remainder < num / 2) {
            remainder++
        }
        if (num % remainder === 0) {
            has = true
            break
        }
    }
    return has
}
/**
 * 冒泡排序
 * @param {*} arr 
 */
export const bubbleSorting = (arr = []) => {
    if (Object.prototype.toString.call(arr) !== '[object Array]') {
        throw new Error('必须是数组')
    }
    if (arr.length < 2) {
        throw new Error('数组长度大于1')
    }
    let pre, middle
    for(let i = 0; i < arr.length - 1; i++) {
        // 最大值放到最后
        for(let j = 0; j < arr.length - 1 - i; j++) {
            middle = arr[j + 1]
            pre = arr[j]
            if (pre > middle) {
                arr[j + 1] = pre
                arr[j] = middle
            }
        }
    }
    console.log('bubbleSorting', arr)
}
/**
 * 计算一个数的阶乘
 * @param {*} num 
 */
export const factorialize = (num) => {
    // let total = num
    // for(let i = 0; i < num - 1; i++){
    //     total = total * num
    // }
    if (num < 1) {
        return 1
    }
    const total = num * factorialize(num - 1)
    return total
}
/**
 * 是否是水仙花数
 * @param {*} num 
 * @returns 
 */
export const isNarcissisticNumber  = (num) => {
    const digits = `${num}`.split('')
    let total = 0
    // let digit = 1
    for(let i = 0; i < digits.length; i++) {
        // digit = digit * 10
        const number = digits[i]
        total = total + number * number * number
    }
    const is = num === total
    return is
}
/**
 * 去平方根
 * @param {*} num 
 * @returns 
 */
export const sqrt = (num) => {
    const total = Math.pow(num, 0.5)
    console.log('平方根', total)
    return total
}
/**
 * 一个字符串中出现次数多次最多的字符
 * @param {*} str 
 */
export const totalMaxChat = (str) => {
    const map = new Map()
    for (let i = 0; i < str.length; i++) {
        let key = str[i]
        if (map.has(key)) {
            map.set(key, map.get(key) + 1)
        } else {
            map.set(key, 1)
        }
    }
    let max = 0, maxKey = ''
    Array.from(map.entries()).forEach(([key, value]) => {
        if (value > max) {
            max = value
            maxKey = key
        }
    })
    console.log(`出现次数最多的${maxKey}, 出现了${max}次`)
}