What is a prime number?
A prime number is a number which divides by 1 and itself.S o when we are taking in the program we have to take and check for the numbers which are not divisible by the half of the number to be checked as a prime number.
eg: If we are checking for 11 as a prime number then it should not be divisible by numbers from 2 to 5(11/2).
Algorithm:
1)Store the memory address of the array in R1 where all the numbers should be checked and in R0 where all the checked prime numbers are stored.
2)Divide the number by 2 and store it in the register R3.
3)Check whether the R3 is 1 if it is one then it is a primenumber.
4)If R3 is not 1 then go on dividing the prime number with all the numbers till R3 is 1(By decrementing R0 by 1).
5)If R3 is one then the number is a prime number as it is not divisible by any number except one and itself.
6)Then store the number in an array where all the prime numbers are stored.
7)Suppose if the remainder dividing A(to be checked as a prime number) by any number is zero then break the loop and check the next number in an array.
Let’s learn how to code to check the number stored in an array is a prime or not and store all the prime numbers in a different array.
Code goes here:
ORG 0000h
LJMP MAIN
ORG 40h
MAIN: MOV R1,#0XA0 ;memory faddress rom where all numbers to be checked are stored
MOV R0,#10H ; memory address to store all the prime numbers from an array.
MOV R2,#10 ; length of array
LABEL5:MOV A,@R1
MOV B,#02
DIV AB ;Dividing the number by 2
MOV R3,A
CJNE R3,#01H,LABEL2 ;Checking whether the number is 2
MOV @R0,A
INC R0
SJMP LABEL4
LABEL1:DEC R3 ; decrementing and checking whether the number is not divisible by all possible values of number/2
CJNE R3,#01H,LABEL2
MOV B,@R1
MOV @R0,B ; moving the prime number to the array
INC R0
SJMP LABEL4
LABEL2:MOV A,@R1
MOV B,R3
DIV AB
MOV R4,B
CJNE R4,#0H,LABEL1 ; checking whether the number is divisible any number
LABEL4:INC R1
DEC R2
CJNE R2,#0H,LABEL5 ; verifying whether the counter has reacged to zero
END