橋本分數式問題的C++演算法

來源:互聯網
上載者:User

用枚舉法,得到結果10個解,各位讀者 可查看結果幫忙審核

之所以使用枚舉法,是因為實現簡單

分析:如果採用回溯法,是否有利於實現演算法的並行計算(如果需要的話?);而採用枚舉,則有利於實現並行

 

/*用枚舉法求解橋本分數式問題  問題:尋找p1(1位元)/p2(2位元)+p3(1位元)/p4(2位元)=p5(1位元)/p6(2位元),每位元取值[1..9]  特點:實現比回溯法簡單*/#include <iostream>#include <stdio.h>#include <string>#include <memory.h>using namespace std;//取得最大公約數int getGCD(int a, int b){int c, r;/*//確保a>bif (a < b){c = a;a = b;b = c;}*/r = a % b;while( r != 0 ){a = b;b = r;r = a % b;}return b;}bool check(int p1, int p2, int p3, int p4, int *cnt, int& p5, int &p6){int pa1, pa2, pbX, gcd, k;bool find;pa1 = p1 * p4;   //同分母后的分子1pa2 = p2 * p3;   //同分母后的分子2//要求:第1個分數的分子小於第2個分數的分子if (p1 > p3) return false;p5 = pa1 + pa2;p6 = p2 * p4;   //同分母后的分母//計算真分數if (p6 < p5) return false;gcd = getGCD(p6, p5);p5 /= gcd;p6 /= gcd;//由真分數依次派生假分數,檢驗是否符合需要find = false;k = 1;while(true)  //p6尾數也不能為0{//如果不滿足條件,則搜尋假分數if (p5 > 9 || p6 > 99) break;if (p5 == p6 % 10 || p5 == p6 / 10 || p6 % 10 == p6 / 10 || cnt[p5] > 0 || p6 % 10 == 0 || cnt[p6 % 10] > 0 || cnt[p6 / 10] > 0){p5 = p5 / k * (k + 1);p6 = p6 / k * (k + 1);k++;}else{find = p6 > 9;break;}}return find;}void Qiaoben(){int val = 123456, tmp, part, p1, p2, p3, p4, p5, p6;int cnts[10] = {0};int cnt = 0;while( true ){next:if (val > 999999) break;  //結束條件//不允許數字重複memset(cnts, 0, sizeof(int) * 10);  //設定10個元素值的計數為0tmp = val;for(int i = 1; i <= 6; i++){part = tmp % 10;tmp /= 10;cnts[part]++;if (cnts[part] > 1 || part == 0){val++;goto next;}}//從val中檢驗等式是否符合條件tmp = val;p4 = tmp % 100;tmp /= 100;p3 = tmp % 10;tmp /= 10;p2 = tmp % 100;tmp /= 100;p1 = tmp;if (check(p1, p2, p3, p4, cnts, p5, p6)){cnt++;printf("%2d: ", cnt);cout << val << p5 << p6 << " ==> " << p1 << "/" << p2 << " + " << p3 << "/" << p4 << " = " << p5 << "/" << p6 << endl;}val++;}}int main(){Qiaoben();return 0;}

 

 

 1: 126578439 ==> 1/26 + 5/78 = 4/39
 2: 132596784 ==> 1/32 + 5/96 = 7/84
 3: 132796548 ==> 1/32 + 7/96 = 5/48
 4: 178439652 ==> 1/78 + 4/39 = 6/52
 5: 196748532 ==> 1/96 + 7/48 = 5/32
 6: 268934517 ==> 2/68 + 9/34 = 5/17
 7: 268951734 ==> 2/68 + 9/51 = 7/34
 8: 456798321 ==> 4/56 + 7/98 = 3/21
 9: 526978413 ==> 5/26 + 9/78 = 4/13
10: 634851927 ==> 6/34 + 8/51 = 9/27

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.