首页 > 代码库 > 汇编语言-求所有的素因子
汇编语言-求所有的素因子
求给定整数的所有素因子
1. 题目:求给定整数的所有素因子
2. 要求:输入一个整数,求出其所有素因子,并表现为乘积方式,求因子的算法用子程序来实现。例如,输入480,输出480=2*2*2*2*2*3*5
C++代码如下
1 //The program is to find all the prime factors of a number 2 //Author:Karllen 3 //Date: 05/22/2014 4 #include <iostream> 5 6 void findPfactor(int n); // Find the factor belongs to prime 7 int main(void) 8 { 9 int n; 10 std::cin>>n; 11 findPfactor(n); 12 system("pause"); 13 return 0; 14 } 15 16 void findPfactor(int n) 17 { 18 int i = 2; 19 while (i<n) 20 { 21 while (n%i==0) //The i is a factor of n 22 { 23 n = n/i; 24 std::cout<<i; 25 std::cout<<‘*‘; 26 } 27 ++i; 28 } 29 std::cout<<n<<std::endl; 30 }
汇编代码如下:
1 ; Example assembly language program 2 ; Author: Karllen 3 ; Date: revised 05/2014 4 5 .386 6 .MODEL FLAT 7 8 ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD 9 10 INCLUDE io.h ; header file for input/output 11 12 cr EQU 0dh ; carriage return character 13 Lf EQU 0ah ; line feed 14 15 .STACK 4096 ; reserve 4096-byte stack 16 17 .DATA ; reserve storage for data 18 flai DWORD ? 19 temp DWORD ? 20 crlf BYTE "*",0 21 eqll BYTE "=",0 22 prompt BYTE "Enter a number to find all the prime factors",cr,Lf,0 23 fl DWORD ? 24 value BYTE 11 DUP(?),0 25 char BYTE 1 DUP(?) 26 27 PUBLIC _start 28 .CODE ; start of main program code 29 _start: 30 output prompt 31 input value,11 32 atod value 33 push eax 34 call byteInput 35 add esp,4 36 37 output eqll 38 39 push eax 40 call findPfactor 41 add esp,4 42 43 INVOKE ExitProcess, 0 ; exit with return code 0 44 45 46 findPfactor PROC NEAR32 ;find the prime of factor 47 push ebp 48 mov ebp,esp 49 50 mov eax,[ebp+8] 51 mov flai,eax 52 mov ecx,2 53 mov ebx,ecx 54 doFind: 55 mov ecx,ebx 56 cmp ecx,flai 57 je endFind 58 doFactor: 59 mov temp,eax 60 cdq 61 idiv ecx 62 ;eax = eax/ecx 63 cmp edx,0 64 jne endFactor 65 ;dtoa value,ecx 66 ;output value 67 push ecx 68 call byteInput 69 add esp,4 70 output crlf 71 72 jmp doFactor 73 endFactor: 74 mov eax,temp 75 inc ebx 76 jmp doFind 77 endFind: 78 pop ebp 79 ret 80 81 findPfactor ENDP 82 83 byteInput PROC NEAR32 84 push ebp 85 mov ebp,esp 86 87 push ebx 88 push eax 89 push edx 90 91 mov fl,0 92 mov ebx,10 93 mov eax,[ebp+8] 94 doWh: 95 cdq 96 idiv ebx 97 push edx 98 inc fl 99 cmp eax,0 100 je enddoWh 101 102 103 jmp doWh 104 enddoWh: 105 106 doPrint: 107 108 cmp fl,0 109 je enddoPrint 110 dec fl 111 pop edx 112 mov char,dl 113 add char,‘0‘ 114 output char 115 jmp doPrint 116 enddoPrint: 117 pop edx 118 pop eax 119 pop ebx 120 pop ebp 121 ret 122 123 byteInput ENDP 124 125 END ; end of source code
测试结果:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。