2012-03-07 77 views
0

嘿所以我正在做一個保理程序,我想知道如果任何人都可以給我任何想法有效的方式來找到兩個數字倍數到指定的數字,並添加到指定的數字。找到什麼2號碼添加到東西,並乘以

例如我可以具有

(A)(B)= 6

A + B = 5

所以基本上我只需要一個方法來找到a和b值。在這種情況下,他們將是2和3.

任何人都可以給我任何想法從哪裏開始?負數也必須考慮使用。

+1

也許這會更適合http://math.stackexchange.com/ – oezi 2012-03-07 15:57:48

+0

鑑於他想在PHP(即計算機算法)中做到這一點,我會說在這裏是適當的。 – thomasrutter 2013-03-01 00:44:03

回答

7

來吧夥計們,有沒有需要循環,只是用簡單的數學來解決這個方程組:

A * B = I;

a + b = j;

a = j/b;

a = i-b;

j/b = i-b;所以:

B + J/B + 1 = 0

b^2 + I * B + J = 0

從這裏,它的一元二次方程,這是微不足道的發現b(只是執行quadratic equation formula),從那裏得到a的值。

編輯:

你去那裏:

function finder($add,$product) 
{ 

$inside_root = $add*$add - 4*$product; 

if($inside_root >=0) 
{ 

    $b = ($add + sqrt($inside_root))/2; 
    $a = $add - $b; 

    echo "$a+$b = $add and $a*$b=$product\n"; 

}else 
{ 
    echo "No real solution\n"; 
} 
} 

活生生的行動:

http://codepad.org/JBxMgHBd

+0

+1,用於查找數學的真實生活應用:) – capi 2012-03-07 20:11:55

3

這裏是我會怎麼做:

$sum = 5; 
$product = 6; 

$found = FALSE; 
for ($a = 1; $a < $sum; $a++) { 
    $b = $sum - $a; 
    if ($a * $b == $product) { 
    $found = TRUE; 
    break; 
    } 
} 

if ($found) { 
    echo "The answer is a = $a, b = $b."; 
} else { 
    echo "There is no answer where a and b are both integers."; 
} 

基本上,$a = 1$b = $sum - $a開始,一次通過它一個步驟,因爲我們後來才知道,$a + $b == $sum始終是真實的,繁衍$a$b到看看他們是否等於$product。如果他們這樣做,那就是答案。

See it working

這是否是最有效方法是非常值得商榷。

2

用乘法,我建議使用模運算符(%),以確定哪些數字整除成像目標號碼:

$factors = array(); 
for($i = 0; $i < $target; $i++){ 
    if($target % $i == 0){ 
     $temp = array() 
     $a = $i; 
     $b = $target/$i; 
     $temp["a"] = $a; 
     $temp["b"] = $b; 
     $temp["index"] = $i; 
     array_push($factors, $temp); 
    } 
} 

這將使你的目標數量一系列因素。

1

這基本上是一套2 simultaneous equations

x*y = a 
X+y = b 

(使用x和y的數學慣例來求解變量,a和b使用任意常數)。

但是該解決方案涉及二次方程(因爲x * y),所以根據a和b的實際值,可能沒有解決方案,或者可能有多個解決方案。