在 C++ 中找到滿足 2/n = 1/x + 1/y + 1/z 的 x、y、z


在這個問題中,我們給定整數 n。我們的任務是找到滿足 2/n = 1/x + 1/y + 1/z 的 x、y、z。

讓我們舉個例子來理解這個問題,

Input : n = 4
Output : 4, 5, 20

解決方案方法

解決這個問題的一個簡單方法是使用 n 的值找到解決方案。

如果 n = 1,則方程無解。

如果 n > 1,則方程的解為 x = n,y = n+1,z = n(n+1)。

解為 $2/n\:=\:1/n\:+1\:(n+1)\:+\:1/(n^*(n\:+\:1))$

示例

程式說明我們解決方案的工作原理

#include <iostream>
using namespace std;
void findSolution(int a, int b, int n){
   for (int i = 0; i * a <= n; i++) {
      if ((n - (i * a)) % b == 0) {
         cout<<i<<" and "<<(n - (i * a)) / b;
         return;
      }
   }
   cout<<"No solution";
}
int main(){
   int a = 2, b = 3, n = 7;
   cout<<"The value of x and y for the equation 'ax + by = n' is ";
   findSolution(a, b, n);
   return 0;
}

輸出

The value of x and y for the equation 'ax + by = n' is 2 and 1

更新於: 2022年2月1日

129 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.