我想在乘法中找到負數的因數
我的方法有些不對勁,它只適用于正數而不是負數
我有這個,但它不適用于負數
function factorMul(num) {
let tryThis1 = Math.floor(
Math.random() * (num - 1 1) 1
)
let tryThis2 = Math.floor(
Math.random() * (num - 1 1) 1
)
if(Math.floor(tryThis1 * tryThis2) !== num) return factorMul(num)
return [tryThis1, tryThis2]
}
當我用負數嘗試時,我得到了最大呼叫堆疊大小
感謝Amirhossein Sefati讓我明白我需要做什么
我有這個代碼,現在它可以作業了!!
function factorMul(num) {
if(String(num).startsWith('-')) {
let positive = parseInt(String(num).replaceAll('-', ''))
let factors = factorMul(positive)
let change = Math.floor(
Math.random() * (2 - 1 1) 1
)-1
factors[change] = parseInt("-" factors[change])
return factors
}
let tryThis1 = Math.floor(
Math.random() * (num - 0 1) 1
)
let tryThis2 = Math.floor(
Math.random() * (num - 0 1) 1
)
if(Math.floor(tryThis1 * tryThis2) !== num) {
return factorMul(num)
}
return [tryThis1, tryThis2]
}
uj5u.com熱心網友回復:
求負數的乘法因子:
- 本質上,要分解一個負數,找到它的所有正因數,然后復制它們并在重復的前面寫一個負號。例如,-3 的正因子是 1 和 3。復制它們會產生 1、3、1、3;在重復項之前寫一個負號會產生 1、3、-1、-3,它們都是 -3 的因數。
因此,在您的代碼中,只需檢查傳遞的數字是否為負數,如果是,則使其為正數,然后當它準備好回傳值時,執行上面的提示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524665.html
下一篇:10位數字和日期時間有什么關系
