资源描述:
《常见算法代码总结》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、常见算法代码总结:1、交换Tmp=a;A=b;B=tmp;2、整数X=int(X)3、奇数、偶数Xmod2=0为偶数Xmod2<>0为奇数4、累加、累乘书本P70例5-45、最大、最小值(书本P97例6-1)DimiAsInteger,a(10)asintegerMax=a(1)Min=a(1)Fori=2ToUBound(a)Ifa(i)MaxThenMax=a(i)EndIfNexti6、选择排序(书本P106例6-6)PrivateSubsort(a()AsInteger)DimtempAsI
2、nteger,nAsInteger,iAsInteger,jAsIntegern=UBound(a)Fori=1Ton-1Forj=i+1TonIfa(i)>a(j)Then'形成递增序列temp=a(i)a(i)=a(j)/p;//a(j)=tempEndIfNextjNextiEndSub7、冒泡排序(书本P157例7-8)OptionExplicitOptionBase1PrivateSubCommand1_Click()DimA()AsInteger,tempAsIntegerDimiAsInteger,jAsIntegerDimNAsInte
3、gerN=6ReDimA(N)RandomizeFori=1ToN'生成数组A(i)=Int(Rnd*99)+1Text1.Text=Text1.Text&Str(A(i))NextiFori=1ToN–1‘冒泡排序Forj=1ToN-iIfA(j)>A(j+1)Thentemp=A(j)A(j)=A(j+1)A(j+1)=tempEndIfNextjNextiFori=1ToN‘输出排序后的数组Text2=Text2&Str(A(i))NextiEndSub1、最大公约数、最小公倍数PrivateSubCommand1_Click()DimRAsIn
4、teger,MAsInteger,NAsInteger,TAsIntegerDimsasinteger,lcdasintegerM=InputBox("PleaseInputnumberA")N=InputBox("PleaseInputnumberB")S=m*n‘两数的乘积=最大公约数*最小公倍数R=MModN'欧几里德法求最大公约数DoWhileR<>0M=NN=RR=MModNLoopMsgBox("最大公约数是:"&N)Lcd=s/nMsgBox("最小公倍数是:"&lcd)EndSub9、素数PrivateFunctionPrime(xAs
5、Integer)AsBoolean‘判断是否是素数过程DimiAsIntegerFori=2Tosqr(x)//或x-1或x/2IfxModi=0ThenExitForNextiIfi>sqr(x)Then//或i>x-1或i>x/2Prime=TrueElsePrime=falseEndIfEndFunction或PrivateFunctionPrime(xAsInteger)AsBoolean‘判断是否是素数过程DimiAsIntegerPrime=falseFori=2Tosqr(x)IfxModi=0ThenExitFunctionNextiP
6、rime=TrueEndFunction10、整数拆分(各位数字)例1:PrivateSubCommand1_Click()DimNAsInteger,IAsInteger,SumAsIntegerN=InputBox("Pleaseinputanumber:")ForI=1ToLen(CStr(N))Sum=Sum+Mid(CStr(N),I,1)NextIPrint"Sum=";SumEndSub或k=val(Text1.text)DoWhilek>0sum=sum+kMod10k=k10LoopPrintsum例:找水仙花数P77例5-911、
7、进制转换例:十进制数转换为二进制数OptionBase0PrivateSubCommand1_Click()DimiAsInteger,dAsIntegerDimb()AsInteger,sAsString,kAsIntegerd=Text1.TextIfd=0ThenText2.Text=0ElseIfd>0ThenDoUntild=0i=i+1ReDimPreserveb(i)b(i)=dMod2d=d2LoopFork=iTo1Step-1s=s&b(k)NextkEndIfEndSub12、质因子DoUntilx<=1IfxModk=0The
8、nList1.AddItemkx=xkElsek=k+1EndIfLoop13、求级数例2: