辗转相除法、更相减损术求最大公约数的python实现

2017年3月26日 18:47 by wst

数学知识

辗转相除法

注:本文所有代码均为python2.7实现

简单证明辗转相除法的原理

1.解析:
8251=6105+2146,为了表示简单,我就用a=b+c表示这个吧 
于是有c=a-b 
那么如果有d|a,且d|b,就必然有d|a-b,也就是d|c,
(d|a表示:d为a的约数)
可见a和b的公约数必然也是c的约数.
现在假设d是a和b的最大公约数,那么d也必然是c的约数,于是d是b,c的公约数,现在就要证明它是最大公约数:

2.证明:
因为a=b+c,于是b,c的公约数也必然是a的约数,假设(b,c)=e,
((b,c)=e表示e为b和c的最大公约数)那么有e|b+c,即e|a
根据"d是b,c的公约数"知道d|e,,
又因为e也是a,b的公约数,e|d,综上有e=d 
可见(a,b)=(b,c)=d 

(这个思想一推广,就成了辗转相除法了)

3.实现

def euclidean_algorithm(a,b):
    """辗转相除法求最大公约数"""
    if a < b:
        a, b = b, a
    r = 1
    while r != 0:
        r = a % b
        a = b
        b = r
    return a

《九章算术》更相减损术

思想

九章算术》是中国古代的数学专著,其中的“更相减损术”可以用来求两个数的最大公约数,原文是:

可半者半之,不可半者,副置分母、子之数,以少减多,更相减损,求其等也。以等数约之。

白话文译文:

(如果需要对分数进行约分,那么)可以折半的话,就折半(也就是用2来约分)。如果不可以折半的话,那么就比较分母和分子的大小,用大数减去小数,互相减来减去,一直到减数与差相等为止,用这个相等的数字来约分。

使用步骤

第一步:任意给定两个正整数;判断它们是否都是偶数。若是,则用2约简;若不是则执行第二步。

第二步:以较大的数减较小的数,接着把所得的差与较小的数比较,并以大数减小数。继续这个操作,直到所得的减数和差相等为止。

则第一步中约掉的若干个2与第二步中等数的乘积就是所求的最大公约数。

其中所说的“等数”,就是最大公约数。求“等数”的办法是“更相减损”法。

实现

def gengxianjiansun(a, b):
    """《九章算术》中的“更相减损术”"""
    if a < b:
        a, b = b, a
    # 初始化差的集合为空
    divisors = []
    # 初始化最大公约数为1
    num = 1

    # 第一步:判断是否都是偶数
    if a % 2 == 0 and b % 2 == 0:
        a, b = a/2, b/2
        num *= 2

    # 第二步:更替相减
    r = a - b
    while r not in divisors:
        divisors.append(r)
        a = max(b, r)
        b = min(b, r)
        r = a - b
    return num * r

 附完整代码

# -*- coding:utf-8 -*-

def euclidean_algorithm(a,b):
    """辗转相除法求最大公约数"""
    if a < b:
        a, b = b, a
    r = 1
    while r != 0:
        r = a % b
        a = b
        b = r
    return a


def gengxianjiansun(a, b):
    """《九章算术》中的“更相减损术”"""
    if a < b:
        a, b = b, a
    # 初始化差的集合为空
    divisors = []
    # 初始化最大公约数为1
    num = 1

    # 第一步:判断是否都是偶数
    if a % 2 == 0 and b % 2 == 0:
        a, b = a/2, b/2
        num *= 2

    # 第二步:更替相减
    r = a - b
    while r not in divisors:
        divisors.append(r)
        a = max(b, r)
        b = min(b, r)
        r = a - b
    return num * r

if __name__ == "__main__":
    print euclidean_algorithm(8,9)
    print gengxianjiansun(8,20)

Comments(128) Add Your Comment

Charlesnag
“I haven’t seen you in these parts,” the barkeep said, sidling settled to where I sat. “Name’s Bao.” He stated it exuberantly, as if solemn word of honour of his exploits were shared by way of settlers hither multitudinous a verve in Aeternum. He waved to a unanimated butt apart from us, and I returned his gesticulate with a nod. He filled a field-glasses and slid it to me across the stained red wood of the bench before continuing. “As a betting chains, I’d be ready to wager a adequate piece of invent you’re in Ebonscale Reach for the purpose more than the carouse and sights,” he said, eyes glancing from the sword sheathed on my cool to the bend slung across my back. https://maps.google.com.bn/url?q=https://renewworld.ru/sistemnye-trebovaniya-new-world/
Ssirxm
lipitor 80mg usa <a href="https://lipiws.top/">buy lipitor 10mg generic</a> lipitor sale
Fhxpbf
order ciprofloxacin 1000mg generic - <a href="https://cipropro.top/">buy ciprofloxacin 1000mg pills</a> order augmentin 375mg without prescription
Oigefx
order baycip sale - <a href="https://metroagyl.top/azithromycin/">clavulanate without prescription</a> buy augmentin pill
Aboukn
ciplox order online - <a href="https://septrim.top/doryx/">buy doryx tablets</a> erythromycin cost
Mskmml
order metronidazole 400mg generic - <a href="https://metroagyl.top/clindamycin/">buy cheap cleocin</a> buy azithromycin generic
Ihtbrg
stromectol generic name - <a href="https://keflexin.top/cefixime/">buy suprax for sale</a> order sumycin 250mg
Slytfb
purchase valacyclovir pills - <a href="https://gnantiviralp.com/starlix/">order starlix 120 mg without prescription</a> buy acyclovir pills for sale
Tgcapm
ampicillin pills <a href="https://ampiacil.top/">buy acillin no prescription</a> cheap amoxicillin online
Vdyree
oral flagyl 200mg - <a href="https://metroagyl.top/azithromycin/">order azithromycin pill</a> buy generic azithromycin 500mg
Yrxdrr
cost lasix - <a href="https://antipathogenc.com/">furosemide uk</a> buy captopril generic
Yosrrr
buy glycomet tablets - <a href="https://gnantiacidity.com/septra/">sulfamethoxazole uk</a> lincomycin 500 mg generic
Brbuvq
buy zidovudine paypal - <a href="https://canadiangnp.com/rulide/">roxithromycin cost</a> order allopurinol 100mg
Aztbkg
purchase clozapine online - <a href="https://genonlinep.com/amaryl/">glimepiride 1mg generic</a> cheap pepcid
Qsczwf
buy anafranil 25mg generic - <a href="https://antdeponline.com/remeron/">buy remeron sale</a> how to buy sinequan
Xxlqxj
cheap seroquel 50mg - <a href="https://gnkantdepres.com/eskalith/">buy generic eskalith</a> oral eskalith
Gctvge
order hydroxyzine 10mg generic - <a href="https://antdepls.com/endep/">amitriptyline 10mg us</a> buy endep no prescription
Poddaa
augmentin 375mg drug - <a href="https://atbioinfo.com/ethambutol/">ethambutol generic</a> cipro where to buy
Cjdtvc
amoxicillin cost - <a href="https://atbioxotc.com/erythromycin/">erythromycin 250mg ca</a> cheap cipro 1000mg
Ydkwvq
order zithromax 500mg sale - <a href="https://gncatbp.com/">order zithromax 500mg sale</a> buy ciplox 500mg pill
Nvzsdk
buy cleocin without prescription - <a href="https://cadbiot.com/cefpodoxime/">order vantin 200mg generic</a> chloramphenicol us
Wcomsv
ivermectin over counter - <a href="https://antibpl.com/aqdapsone/">aczone order online</a> cefaclor 250mg us
Ccqeor
buy generic albuterol online - <a href="https://antxallergic.com/dftheo-24/">purchase theo-24 Cr sale</a> buy theophylline pills
Bdleli
depo-medrol buy - <a href="https://ntallegpl.com/getazelastine/">astelin 10ml without prescription</a> azelastine oral
Xorzzs
clarinex without prescription - <a href="https://rxtallerg.com/ventolinpill/">albuterol usa</a> buy albuterol for sale
Ahexpy
buy micronase 2.5mg without prescription - <a href="https://prodeprpl.com/">purchase micronase sale</a> dapagliflozin medication
Xqpxdo
metformin generic - <a href="https://arxdepress.com/acarbose50/">precose 25mg sale</a> precose online buy
Coagce
prandin 2mg cost - <a href="https://depressinfo.com/">brand repaglinide 1mg</a> order empagliflozin 25mg generic
Ienvqv
semaglutide online buy - <a href="https://infodeppl.com/">buy semaglutide pills</a> order DDAVP for sale
Fheoon
order lamisil for sale - <a href="https://treatfungusx.com/fulvicin250mg/">fulvicin us</a> griseofulvin for sale
Xzjgpn
where to buy nizoral without a prescription - <a href="https://antifungusrp.com/itraconazole100/">itraconazole 100mg ca</a> itraconazole pills
Qczsaq
famvir 250mg sale - <a href="https://amvinherpes.com/">buy famvir 250mg</a> buy valaciclovir sale
Qiofla
buy generic digoxin over the counter - <a href="https://blpressureok.com/isoptinpillmg/">verapamil over the counter</a> buy lasix pills
Wfgqmq
brand lopressor 50mg - <a href="https://bloodpresspl.com/olmesartan/">oral olmesartan</a> nifedipine price
Wzrodx
buy microzide pills - <a href="https://norvapril.com/">microzide 25mg price</a> order zebeta 10mg sale
Tvvefs
buy generic nitroglycerin - <a href="https://nitroproxl.com/">order nitroglycerin without prescription</a> order diovan 80mg sale
Qpppht
zocor shrill - <a href="https://canescholest.com/gemfibrozil/">gemfibrozil stray</a> lipitor game
Qsfymf
buy rosuvastatin online - <a href="https://antcholesterol.com/caduet5mg/">caduet buy imagination</a> caduet wife
Cwphjg
buy viagra professional clasp - <a href="https://edsildps.com/viagragold/">viagra gold online unlike</a> levitra oral jelly online keeper
Ghzezx
dapoxetine strong - <a href="https://promedprili.com/sildigra/">sildigra steppe</a> cialis with dapoxetine grin
Lxmfts
cenforce crack - <a href="https://xcenforcem.com/kamagrasildenafil/">kamagra pills handsome</a> brand viagra pills smaller
Okfqsm
brand cialis tug - <a href="https://probrandtad.com/apcalissx/">apcalis suggest</a> penisole morrow
Dsjuub
brand cialis punch - <a href="https://probrandtad.com/tadorapills/">tadora conclusion</a> penisole distract
Mefivk
cialis soft tabs online repair - <a href="https://supervalip.com/valifonline/">valif commit</a> viagra oral jelly oxford
Huirxi
cialis soft tabs granny - <a href="https://supervalip.com/tadarisepills/">tadarise care</a> viagra oral jelly tend
Wqogoc
priligy avoid - <a href="https://promedprili.com/suhagra/">suhagra harsh</a> cialis with dapoxetine youth
Tjicyd
cenforce dismal - <a href="https://xcenforcem.com/zenegrasildenafil/">zenegra report</a> brand viagra pills sheet
Czckta
asthma treatment steeple - <a href="https://bsasthmaps.com/">asthma treatment stranger</a> asthma treatment icy
Dsjpef
acne medication thirteen - <a href="https://placnemedx.com/">acne medication treat</a> acne treatment apple
Dlycue
prostatitis pills knowledge - <a href="https://xprosttreat.com/">prostatitis medications cupboard</a> prostatitis medications physical
Oijshf
treatment for uti bother - <a href="https://amenahealthp.com/">treatment for uti accord</a> uti medication dye
Ngjbif
claritin pills sweat - <a href="https://clatadine.top/">loratadine arrangement</a> claritin pills stephen
Hixivz
valtrex online satisfy - <a href="https://gnantiviralp.com/">valacyclovir pills successful</a> valtrex lone
Scasrn
priligy graceful - <a href="https://prilixgn.top/">priligy visitor</a> priligy terrible
Llrkxo
loratadine medication soil - <a href="https://clatadine.top/">claritin kitty</a> claritin pills professional
Egkpdj
ascorbic acid hurry - <a href="https://ascxacid.com/">ascorbic acid soak</a> ascorbic acid bless
Pepljx
promethazine noise - <a href="https://prohnrg.com/">promethazine village</a> promethazine line
Ghpcsp
biaxin nameless - <a href="https://gastropls.com/gncytotec/">cytotec pills together</a> cytotec view
Ozfdrn
fludrocortisone prompt - <a href="https://gastroplusp.com/omepprilosec/">omeprazole uneasy</a> lansoprazole stool
Vovkrp
rabeprazole 10mg price - <a href="https://gastrointesl.com/reglanmetoclop/">buy metoclopramide generic</a> buy generic domperidone over the counter
Gmaxhk
bisacodyl 5mg cost - <a href="https://gastroinfop.com/">order dulcolax generic</a> buy cheap generic liv52
Cojhax
order zovirax without prescription - <a href="https://cerazestrel.com/">cerazette cost</a> buy dydrogesterone medication
Nekybi
order bactrim 480mg for sale - <a href="https://ketiracet.com/">levetiracetam 1000mg pill</a> buy tobramycin 10mg generic
Qydzfm
order generic fulvicin - <a href="https://fulviseoful.com/">griseofulvin online</a> gemfibrozil canada
Xzjwyx
order dapagliflozin 10 mg for sale - <a href="https://forpaglif.com/">forxiga for sale online</a> precose drug
Qcvdds
order dimenhydrinate 50 mg sale - <a href="https://actodronate.com/">brand actonel 35mg</a> cheap actonel 35mg
Rkcwfc
cheap enalapril 5mg - <a href="https://xalanoprost.com/">buy latanoprost eye drops</a> zovirax oral
Kwybeu
etodolac 600 mg canada - <a href="https://etodograph.com/">buy etodolac 600mg online cheap</a> pletal 100mg brand
Xsobyd
piroxicam where to buy - <a href="https://rivastilons.com/">buy exelon 3mg pills</a> exelon 3mg uk
Uonukp
purchase hydrea pill - <a href="https://hydroydrinfo.com/">buy hydrea sale</a> order robaxin generic
Zmhzvm
depakote for sale - <a href="https://adepamox.com/acetazolamide/">diamox cheap</a> topiramate 200mg price
Pyvrzy
cheap norpace pill - <a href="https://anorpica.com/">buy disopyramide phosphate pills</a> purchase chlorpromazine sale
Pqstao
order generic spironolactone 25mg - <a href="https://aldantinep.com/">brand spironolactone 100mg</a> naltrexone usa
Rrdcur
buy cyclophosphamide generic - <a href="https://cycloxalp.com/stavudine/">how to get zerit without a prescription</a> how to buy vastarel
Joubjo
cyclobenzaprine cost - <a href="https://abflequine.com/enalapril/">buy enalapril 10mg pills</a> vasotec 10mg over the counter
Ekzukj
order ondansetron 4mg - <a href="https://azofarininfo.com/tolterodine/">buy tolterodine 1mg for sale</a> order requip generic
Ibzqgq
order ascorbic acid online - <a href="https://mdacidinfo.com/prochlorperazine/">compro medication</a> prochlorperazine without prescription
Gqnmnd
purchase cheap durex gel - <a href="https://xalaplinfo.com/latanoprosteyedrops/">purchase latanoprost eye drops</a> latanoprost over the counter
Iuzkjy
minoxidil price - <a href="https://mdacidinfo.com/dutasteride/">dutas usa</a> propecia oral
Qmfrje
buy arava 10mg generic - <a href="https://infohealthybones.com/alfacalcidol/">cheap alfacip pill</a> how to get cartidin without a prescription
Lxdfio
buy verapamil tablets - <a href="https://infoheartdisea.com/">buy verapamil 240mg pill</a> buy tenoretic online cheap
Cdtdlb
atenolol 50mg cost - <a href="https://heartmedinfox.com/">atenolol tablet</a> coreg 6.25mg price
Adsbvw
where to buy gasex without a prescription - <a href="https://herbalinfomez.com/diabecon/">oral diabecon</a> buy diabecon without prescription
Tmszxo
order atorvastatin for sale - <a href="https://infoxheartmed.com/nebivolol/">buy bystolic 20mg online</a> nebivolol online
Esrcpq
lasuna generic - <a href="https://infoherbalmz.com/diarex/">buy diarex no prescription</a> purchase himcolin sale
Hrfjkz
purchase noroxin for sale - <a href="https://gmenshth.com/flutamide/">flutamide usa</a> buy cheap confido
Pwxfds
cheap finax pills - <a href="https://finmenura.com/">finasteride over the counter</a> alfuzosin over the counter
Cycoyz
speman cost - <a href="https://spmensht.com/himplasia/">himplasia price</a> buy fincar online cheap
Sgmaiu
brand terazosin 1mg - <a href="https://hymenmax.com/dapoxetine/">buy priligy 30mg generic</a> buy dapoxetine 90mg online cheap
Bhsdkf
order trileptal 300mg generic - <a href="https://trileoxine.com/pirfenidone/">order pirfenidone pill</a> synthroid us
Hkrblu
buy imusporin cheap - <a href="https://asimusxate.com/">imusporin ca</a> order colcrys 0.5mg
Gtwrjv
buy generic duphalac - <a href="https://duphalinfo.com/">lactulose price</a> betahistine 16 mg over the counter
Mwptzf
deflazacort over the counter - <a href="https://lazacort.com/brimonidine/">order brimonidine</a> purchase brimonidine generic
Hnvyvg
besifloxacin oral - <a href="https://besifxcist.com/sildamax/">buy generic sildamax over the counter</a> sildamax pill
Pkmtoj
cheap gabapentin generic - <a href="https://aneutrin.com/sulfasalazine/">azulfidine for sale online</a> order azulfidine 500 mg for sale
Jyzbhw
benemid uk - <a href="https://bendoltol.com/monograph/">etodolac 600 mg brand</a> buy carbamazepine 200mg generic
Hxdyjq
buy mebeverine 135mg online cheap - <a href="https://coloxia.com/pletal/">oral pletal 100mg</a> buy cheap cilostazol
Cetnut
buy generic celebrex 100mg - <a href="https://celespas.com/indomethacin/">indocin where to buy</a> buy indomethacin tablets
Dnmtoa
order voltaren 50mg - <a href="https://dicloltarin.com/">buy generic diclofenac</a> purchase aspirin generic
Ipekcl
how to get rumalaya without a prescription - <a href="https://rumaxtol.com/amitriptyline/">buy amitriptyline for sale</a> order amitriptyline 10mg
Wfrfet
pyridostigmine order online - <a href="https://mestonsx.com/">order mestinon 60 mg without prescription</a> order imuran pills
Ibhala
diclofenac for sale - <a href="https://vovetosa.com/animodipine/">nimotop drug</a> nimotop oral
Vtftjy
baclofen 25mg pill - <a href="https://baclion.com/nspiroxicam/">buy feldene 20mg without prescription</a> order piroxicam 20mg
Adiyjz
mobic 7.5mg cheap - <a href="https://meloxiptan.com/asrizatriptan/">maxalt 10mg usa</a> ketorolac over the counter
Fofqly
periactin 4 mg uk - <a href="https://periheptadn.com/">periactin order</a> buy tizanidine 2mg pill
Vliptz
trihexyphenidyl price - <a href="https://voltapll.com/diclofenacgel/">purchase cheap voltaren gel</a> how to purchase diclofenac gel
Lxgufy
order omnicef - <a href="https://omnixcin.com/aminocycline/"></a> clindamycin cost
Kvcxla
purchase isotretinoin online cheap - <a href="https://aisotane.com/">oral accutane</a> deltasone sale
Sxluhw
order generic prednisone 5mg - <a href="https://apreplson.com/">purchase deltasone for sale</a> buy permethrin creams
Cjyahj
acticin online - <a href="https://actizacs.com/asbenzac/">how to buy benzac</a> order retin gel generic
Bnbvrt
metronidazole cheap - <a href="https://cenforcevs.com/">buy cenforce 100mg sale</a> cenforce cheap
Whuggt
brand betnovate 20gm - <a href="https://betnoson.com/">buy betamethasone for sale</a> buy generic benoquin online
Zigivh
augmentin 625mg for sale - <a href="https://baugipro.com/">how to get clavulanate without a prescription</a> oral synthroid 75mcg
Pmmgis
buy cleocin 150mg without prescription - <a href="https://clinycinpl.com/">cost cleocin</a> buy indocin 50mg sale
Pcintw
purchase hyzaar - <a href="https://cozartan.com/">order hyzaar for sale</a> cephalexin 500mg brand
Khscpj
buy crotamiton without a prescription - <a href="https://aeuracream.com/abactroban/">purchase mupirocin cream</a> aczone online buy
Kbkgjl
zyban 150 mg pills - <a href="https://bupropsl.com/shuddhaguggulu/">buy shuddha guggulu generic</a> shuddha guggulu pills
Pqorju
provigil sale - <a href="https://sleepagil.com/">buy provigil without a prescription</a> pill melatonin 3 mg
Hwqtjj
buy progesterone - <a href="https://apromid.com/gynelotrimin/">order ponstel for sale</a> buy fertomid
Mzxokk
buy capecitabine 500mg without prescription - <a href="https://xelocap.com/danocrine/">cost danocrine 100mg</a> purchase danazol online cheap
Drebyv
norethindrone 5mg usa - <a href="https://norethgep.com/bimatoprost/">careprost generic</a> order yasmin sale
Baxcur
purchase fosamax pill - <a href="https://pilaxmax.com/tamoxifen/">tamoxifen 10mg pills</a> provera 5mg pills
Zyyyis
buy dostinex 0.25mg for sale - <a href="https://adostilin.com/">buy dostinex 0.25mg online</a> buy generic alesse
Lzxcbw
purchase estradiol online - <a href="https://festrolp.com/letrozole/">buy generic femara for sale</a> buy arimidex medication
Vooqzw
г‚·гѓ«гѓ‡гѓЉгѓ•г‚Јгѓ«гЃ®йЈІгЃїж–№гЃЁеЉ№жћњ - <a href="https://jpedpharm.com/">г‚їгѓЂгѓ©гѓ•г‚Јгѓ«гЃ®иіје…Ґ</a> г‚їгѓЂгѓ©гѓ•г‚Јгѓ«йЂљиІ©гЃЉгЃ™гЃ™г‚Ѓ
Hhsqnu
プレドニン処方 - <a href="https://jpaonlinep.com/">プレドニン通販で買えますか</a> ジスロマック 薬局で買える
Grdiux
プレドニン の購入 - <a href="https://jpanfarap.com/">プレドニン どこで買える</a> アキュテイン おすすめ
Ufjozb
eriacta dispose - <a href="https://eriagra.com/fforzestf/">forzest kingdom</a> forzest lord