Inline Assembly Code (Cont.)


Code Example—Checking a Prime Number
An integer n is called a prime number if the only positive integers that divide n are 1 and n itself. Integers that are not prime are called composite. Here are the first few prime numbers:

 
   2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...
To check if a number n>2 is prime, repeatedly divide it by numbers m, where 2≤m≤½×n. The number is prime if none of the remainders is zero.

 Prime.cpp 

 
// Prime.cpp——Checking a prime number


 
#include  <iostream>

 
#include  "CheckPrime.h"

 
using namespace  std;


 
int   number;

 
char  result;



 
int  main( ) {

 
  cout << "Enter the number to be checked (>1): ";

 
  cin  >> number;


 
  cout << "The number " << number;

 
  if ( number < 2 )

 
    cout << " must be greater than 1.";

 
  else if ( ( number == 2 ) || ( number == 3 ) )

 
    cout << " is a prime number.";

 
  else {
       
if ( result == 't' ) cout << " is a prime number."; else cout << " is NOT a prime number."; } cout << endl << endl; return( 0 ); }
 CheckPrime.h 

 
// CheckPrime.h——Containing a single function prototype


 
void  CheckPrime( int number, char* result );
 CheckPrime.cpp 

 
// CheckPrime.cpp——Containing an asm block


 
#include  "CheckPrime.h"


 
void  CheckPrime( int number, char* result ) {

 
  __asm {

 
       mov  ecx, number
           // (Shift right) ECX = ECX / 2    
L1: mov edx, 0 mov eax, number // EDX:EAX = Dividend div ecx // ECX = Divisor cmp edx, 0 // EDX = Remainder je L2 dec ecx cmp ecx, 1 jg L1 mov esi, result mov [esi], 't' jmp L3 L2: mov esi, result mov [esi], 'f' L3: } // asm }


      “I’m not arguing, I’m just explaining why I’m right.”    
      ― Unknown