Thursday 21 March 2013

java program


import java.util.*;
import java.awt.*;
import java.awt.event.*;
class Drawframe
extends Frame
{
int mx1=0, my1=0, mx2=20, my2=50;
Vector px= new Vector();
Vector py= new Vector();
int pointn=0;
int pcount=0;
Integer intg;
public Drawframe()
{
px.insertElementAt(new Integer(mx1), pointn);
py.insertElementAt(new Integer(my1), pointn);
++pointn;
px.insertElementAt(new Integer(mx2), pointn);
py.insertElementAt(new Integer(my2), pointn);
addMouseListener(new Madapter(this));
addWindowListener(new Wadapter(this));
}
public void paint(Graphics gp)
{
gp.drawString("pen tool demo",20,40);
pcount=px. size();
for (int i=0;i<pcount-1;i++)
{
int tx1= ((Integer)px.elementAt(i)).intValue();
int tx2= ((Integer)px.elementAt(i+1)).intValue();
int ty1= ((Integer)py.elementAt(i)).intValue();
int ty2= ((Integer)py.elementAt(i+1)).intValue();
gp.drawLine(tx1,ty1,tx2,ty2);
}
}
}
class Wadapter
extends WindowAdapter
{
Drawframe df;
Wadapter(Drawframe dfram)
{
df=dfram;
}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
class Madapter
extends MouseAdapter
{
Drawframe df;
Madapter(Drawframe dfram)
{
df=dfram;
}
public void mousePressed(MouseEvent me)
{
int x1=me.getX();
int y1=me.getY();
df.pointn++;
(df.px).insertElementAt(new Integer(x1), df.pointn);
(df.py).insertElementAt(new Integer(y1), df.pointn);
}
public void mouseDragged(MouseEvent me)
{
int x2=me.getX();
int y2=me.getY();
df.pointn++;
(df.px).insertElementAt(new Integer(x2), df.pointn);
(df.py).insertElementAt(new Integer(y2), df.pointn);
df.repaint();
}
}
class prob171
{
public static void main(String args[])
{
Drawframe frm= new Drawframe();
frm.setSize(300,250);
frm.setTitle("pen Tool Demonstration");
frm.setVisible(true);
}
}

Additional Features


Additional Features

The Keil IDE allows you to enter a number of specific commands while debugging. These features are
enabled via the Command tag on the Output Window (by default this is set on the Build tab). Options
include writing values to ports, displaying memory ranges, assigning values to registers and several others.
Integrated auto-complete functionality makes using this functionality fairly transparent.
Proteus VSM offers a number of useful visual animation options including Logic State of Pins and Wire
Voltage by colour. These can be useful in providing a quick check of obvious problems before proceeding to
debug in depth.

Stepping through the code


Stepping through the code

It is generally considered easier to control the debug process at the level of the program files rather than
through the disassembly. Although this is again a personal choice we will work from our C program file and
assume that users who prefer to work with the assembly language can extrapolate the principles involved.
You can view the calc.c file by selecting it from the Window menu. As we stand we can either step into the
initialise routine or step over the routine and on to the next part of the program. For our purposes assume
that we are not interested in this routine and so we want to run the simulation until we reach the entry point
of the main function. We can do this in one of two ways:
·Set another breakpoint at the point to which we want to advance and then select the Run command from
the Debug menu.
·Place the cursor on the line to which we wish to advance and select the Run to Cursor Line command
from the Debug menu.
Using one of these methods advance the simulation over the initialise and output functions coming to halt at
the line reading:
calc_evaluate(); (line 29)
Looking at ISIS we should now see some changes – the LCD display has initialized and the digit ‘0’ is
displayed. Now let’s examine the calculator in action. We will set a breakpoint at the point of receiving a valid
digit, i.e. on the line:
*bufferptr = key; (line 52)
We can set the simulation running and use the keypad in ISIS to enter a digit. Do this, entering the digit ‘7’
on the keypad, and then view the disassembly in the Keil window.
We can immediately see from the red rectangle in the disassembly window that we have stopped at a
breakpoint. This tells us that we have received a valid digit from the keypad. We will now take a slightly more
in depth look at how this digit is passed through the program.
Disassembly in Detail
The first thing that happens in the disassembly is that we move the contents of 0x0B and 0x0C into the Data
Pointer. Examination of the Internal Memory window in either ISIS or Keil reveals that this value is 0x0009.
Single step twice over these instructions and you should see that the value of the Data Pointer has indeed
changed correctly.
Next we move the contents of 0x08 into the Accumulator. Again, investigation reveals that this value is
0x37 which is consistent with the result after stepping past the instruction.
Finally we move the contents of the Accumulator into the address specified by the Data Pointer. A further
single step followed by an examination of the memory windows will confirm that this has happened. In
essence we have moved the ASCII value for the digit seven into a memory location (which happens to serve
as the first element of the specified array) which correctly reflects the current line in Calc.c.
The next line in our C file is a call to another routine taking a character pointer as an argument:

We can see from the disassembly that the next three instructions move values into registers R1-R3. These
instructions are followed by a ‘long call’ instruction which clearly corresponds to our function call in the C
program.
The Keil compiler by default passes generic pointers using three bytes, where the first byte specifies the
memory type and the second and third bytes specify the high and low order bytes of the offset respectively.
In our case this translates to be the external data memory space with an offset of nine. Again, after single
stepping, we can confirm from our memory windows that this location contains the value of our digit.
Note: The Keil C51.pdf detailing the operation of the compiler is available from the Books tab on the left
hand pane of the Keil IDE or from the website.
We now have the choice of entering the routine via the Step command or advancing beyond the routine via
the Step Over command. In order to follow our entered digit we should step into this routine.
We can see that the first thing that happens in our new routine is that the parameter passed in registers R1-
R3 is stored freeing up these registers for local use.
Next we clear the accumulator and store it’s value in memory locations 0x11 and 0x12. This corresponds
to the execution of the first line in the calc_display function:
INT data i = 0; (line 257)
Stepping through the disassembly we find ourselves at another ‘long call’ instruction. This corresponds to
the call to the clearscreen() function in our C source file and, as such is not relevant to the current
exercise. Use the Step Over instruction to advance the simulation beyond this instruction..
Note: Caution is required when stepping over functions during the debug of a real problem. Bear in mind that
not only are you stepping over the execution of the function in question but also of any functions called by
that function.
A quick check of the ISIS display at this point will confirm that the LCD display has indeed been cleared.
The next few instructions are quite involved and deal with the conditions specified in the C source file for
allowing a character to be outputted to the display. Given that we know that our character is valid and will
pass these checks we won’t concern ourselves with them but simply single step through them.
The by now rather familiar action of loading registers R1-R3 with our parameter comes next before yet
another function call – this time to the assembly language LCD controller routine.
At this point we will leave the trail and step over this function call (feel free to follow through the routines if
you want). This has the immediate and rather gratifying effect that the digit seven is now correctly shown in
the LCD display in ISIS.
Obviously there is a lot more to the debugging process than we have covered here but hopefully you should
have some idea of the possibilities and advantages of using Proteus VSM and the Keil IDE in partnership to
debug 8051 circuits. The next section of the document lists some other, less commonly used features of the
products.

Debugging the circuit.


Debugging the circuit.

Starting a Debug Session
The first task here is to set a breakpoint in the program code from within the Keil IDE. A suitable point would
be the entrance to the LCD initialisation routine so select calc.c from the left hand pane and place the mouse
cursor on the line with the code:
initialise(); // Initialize the LCD
From the Debug menu select the Insert/Remove Breakpoint command – you should now see a red rectangle
at the start of the line which represents the breakpoint.
Note: If you want to specify a shortcut key for this or any other commonly used functions you do so via the
Options command on the View menu.
Now select the Start/Stop Debug Session option from the Debug menu. This will initialise the debug session
and should have two noticeable effects.
1.The main Keil window will change and display an assembly language listing. A small yellow arrow on the
left hand side will indicate the current instruction as dictated by the breakpoint. The left hand pane of the
Keil window will change to display the register bank and system registers.
2.Simulation will start in ISIS and then pause prior to execution of the instruction specified by the
breakpoint. The status bar at the bottom of the application window will display the amount of time that
the simulation has run and the PC value when the breakpoint is reached.
Note: If you are running both applications on the same computer you can toggle between them using
ALT+TAB.
Additional Debug Information
The Peripherals menu in the Keil IDE allows you to view the status and values of the Interrupt System,
Timers, IO Ports, A/D Converter and the Serial Peripheral Interface. Additionally, you can look at the
memory contents and use the Watch Window via the View menu.
ISIS provides a series of popup windows accessible from the Debug menu which allow you to view memory
contents register values as well as use the configurable Watch Window. The values displayed in these
should of course be identical to those in the Keil environment at any stage of the simulation and as such you
can use either or both according to your personal preferences.
Another useful feature of ISIS is that you can visually display the logic states of the pins throughout the
simulation. This option is accessible through the Set Animation Options command on the Template menu
and provides an excellent snapshot of the state of the circuit.
Note: Both ISIS and Keil use highlighting to indicate that the value of an item in the watch window (or a
register in the left pane of the Keil IDE) has changed since the last paused state.
Debugging Commands
The following commonly used debugging commands are available within the Keil environment.
Go
When paused this command will release the simulation back into free running mode.
Step
When paused this command will advance the simulation by one instruction.
Step Over
When paused this command will step over the current instruction and pause at the following instruction.
Step Out of Current Function
When paused this command will exit the current routine pausing at the instruction subsequent to the return.

Run to Cursor Line
When paused this command will release the simulation into free running mode until the line of code where
the mouse cursor is currently positioned is reached.
Stop Running
When running this command will pause the simulation at the instruction currently being executed.
It is important to realise that these commands operate at the level of the 8051 assembly language and not at
the level of the C source file. A Step Over command, for example, will not advance the simulation over the
current line in the C file but rather step over the current instruction as shown in the disassembly window.

Preparing a Debug Session


Preparing a Debug Session

For the purposes of this documentation we will use the calculator project as given in the samples directory of
the Proteus installation. A guide to configuring the applications is given below:
·Start up ISIS and load the Keil Calculator sample design. Typically this can be found in
C:\Program Files\ Labcenter Electronics\Proteus 5.2 Professional\Samples\C51 Calculator\
Note that if you have the demonstration version of the Proteus software any alteration to the design will
disable the simulation functionality.
·Select the Use Remote Debug Monitor option from the Debug menu. A message to the effect that the
Virtual Debug Monitor is enabled should appear on the status line (at the bottom of the application
window). If you get error messages it is most likely that there is a problem with your TCP/IP
configuration.
·Start up the Keil environment and load in the project CALC.UV2 which, by default, can be found via the
above path. If you are using the demonstration version of the Keil software note that it is limited to 2K
code. Should you decide to change the code and exceed this limitation the program will not compile.
·Invoke the Options for Target ‘Target 1’ command from the Project Menu.
·Select the Debug tab of this dialogue form and change the selection from the Use Simulator option to
the Use Keil Monitor-51 Driver option on the right hand side of the dialogue form.
·Change the combo-box to select the Proteus VSM Monitor-51 Driver option. If you do not have this
option please refer to the instructions above for setting up the installations.
·If you intend on running ISIS on a second computer, click the Settings button and enter the IP address
or DNS name of the target computer into the Host IP Address field.
·In most circumstances (and for the current demonstration) you should select Load Application at Startup
and Go Until Main. Selecting the former means that it is not necessary to specify the program file for the
8051 model in ISIS as UV2 will load the program into the model at the start of each debugging session.
The Keil configuration Dialogue form showing the correct setup for debugging in conjunction with Proteus
VSM.
You should now have a project loaded in Keil which is configured to control a debugging session on the
circuit loaded in ISIS.

Proteus VSM and Keil Development Tools

Proteus VSM and Keil Development Tools

Introduction
This document is intended to provide instruction for configuring Proteus VSM to work with the Keil IDE. It
also walks through some basic debugging techniques and provides a short tutorial on debugging a simulated
VSM circuit with the Keil IDE. It is not intended in any way to provide a complete list of the features of either
product but rather is meant to supply some specific information on the interoperability of the two
applications.
Getting Started
For the purposes of the following discussion we will assume that both Proteus VSM and the Keil software
has been installed in the default directories on your computer. You will be able to follow the subsequent
steps with demonstration versions of both packages although you will find that you need to purchase the
following VSM components if you want to simulate your own designs.
·Proteus VSM Professional (Schematic Capture and Simulation Engine).
·MCS8051/52 Microcontroller Family.
·Peripherals Library.
Should you wish to write programs greater that 2K in size you will also need to purchase a Professional
version of the Keil IDE.
How does it work?
Interaction between Proteus and the Keil IDE is achieved via the Virtual Debug Monitor (VDM) Interface.
This interface defines a mechanism whereby the Keil IDE can control a VSM simulation session in much the
same way as it might control an in-circuit emulator.
Actual communication is achieved through TCP/IP. This has the advantage that a debugging session can be
run either on one computer or on two computers without the need for any external hardware other than a
typical office network.
How do I set it up?
Although a lot of the hard work is done for you, some manual configuration is still necessary for successful
communication. A step by step guide is given below.
·Ensure that TCP/IP networking is installed on the computer(s) you are going to be using. Almost all user
will have this installed by default but it is easily checked. Look for TCP/IP under the following path:
Control Panel – Network –Protocols (Windows NT) or
Control Panel – Network – Configuration (Windows 95/98)
·Copy the VDM51.dll file from the MODELS directory of your Proteus VSM Installation to the BIN
directory of your Keil installation. Typically these two directories are located at:
C:\Program Files\Labcenter Electronics\Proteus 5.2 Professional\MODELS
and
C:\KEIL\C51\BIN
·Using NOTEPAD (or your favourite text editor), edit the TOOLS.INI file that is located in the file to which
you have installed the Keil software. The full path to this file is typically C:\Keil\Tools.ini.
Towards the bottom of this file under the section [C51] you will find the line
TDRV0=BIN\MON51.DLL (“Keil Monitor-51 Driver”)
Immediately below this add a line that specifies the location of the copied VDM51.DLL . By default this
will be
TDRV1=BIN\VDM51.DLL (“Proteus VSM Monitor-51 Driver”)
This done, you can now save the TOOLS.INI file.
Note: If you have the Keil application open you will need to close it down before the above changes will take
effect.
You should now have configured the Keil IDE to accept the VDM driver allowing communication between the
applications. The next step is to prepare a Keil project for debugging under Proteus VSM.

Testing for Primality


Testing for Primality

For many cryptographic algorithms, it is necessary to select one or more very large prime numbers at random. Thus we are faced with the task of determining whether a given large number is prime. There is no simple yet efficient means of accomplishing this task.
In this section, we present one attractive and popular algorithm. You may be surprised to learn that this algorithm yields a number that is not necessarily a prime. However, the algorithm can yield a number that is almost certainly a prime. This will be explained presently. We also make reference to a deterministic algorithm for finding primes. The section closes with a discussion concerning the distribution of primes.

Miller-Rabin Algorithm

[6] Also referred to in the literature as the Rabin-Miller algorithm, or the Rabin-Miller test, or the Miller-Rabin test.
The algorithm due to Miller and Rabin [MILL75, RABI80] is typically used to test a large number for primality. Before explaining the algorithm, we need some background. First, any positive odd integer n 3 can be expressed as follows:
n 1 = 2kq with k > 0, q odd
To see this, note that (n 1) is an even integer. Then, divide (n 1) by 2 until the result is an odd number q, for a total of k divisions. If n is expressed as a binary number, then the result is achieved by shifting the number to the right until the rightmost digit is a 1, for a total of k shifts. We now develop two properties of prime numbers that we will need.
Two Properties of Prime Numbers
The first property is stated as follows: If p is prime and a is a positive integer less than p, then a2 mod p = 1 if and only if either a mod p = 1 or a mod p= 1 mode p = p 1. By the rules of modular arithmetic (a mode p) (a mode p) = a2 mod p. Thus if either a mode p = 1 or a mod p = 1, then a2 mod p = 1. Conversely, if a2 mod p = 1, then (a mod p)2 = 1, which is true only for a mod p = 1 or a mod p = 1.
The second property is stated as follows: Let p be a prime number greater than 2. We can then write p 1 = 2kq, with k > 0 q odd. Let a be any integer in the range 1 < a < p 1. Then one of the two following conditions is true:
  1. aq is congruent to 1 modulo p. That is, aq mod p = 1, or equivalently, aq 1 (mod p).
  2. One of the numbers aq, a2q, a4q,..., a2k-1q is congruent to 1 modulo p. That is, there is some number j in the range (1 j k) such that a2j-1q mod p = 1 mod p = p 1, or equivalently, a2j-1q 1 (mod p).
Proof: Fermat's theorem [Equation (8.2)] states that an1 1 (mod n) if n is prime. We have p 1 = 2kq. Thus, we know that ap1 mod p = a2kq mod p = 1. Thus, if we look at the sequence of numbers
Equation 8-6

we know that the last number in the list has value 1. Further, each number in the list is the square of the previous number. Therefore, one of the following possibilities must be true:
  1. The first number on the list, and therefore all subsequent numbers on the list, equals 1.
  2. Some number on the list does not equal 1, but its square mod p does equal 1. By virtue of the first property of prime numbers defined above, we know that the only number that satisfies this condition p 1 is So, in this case, the list contains an element equal to p 1.
    This completes the proof.
Details of the Algorithm
These considerations lead to the conclusion that if n is prime, then either the first element in the list of residues, or remainders, (aq, a2q,..., a2k-1q, a2kq) modulo n equals 1, or some element in the list equals (n 1); otherwise n is composite (i.e., not a prime). On the other hand, if the condition is met, that does not necessarily mean that n is prime. For example, if n = 2047 = 23 x 89, then n 1 = 2 x 1023. Computing, 21023 mod 2047 = 1, so that 2047 meets the condition but is not prime.
We can use the preceding property to devise a test for primality. The procedure TEST takes a candidate integer n as input and returns the result composite if n is definitely not a prime, and the result inconclusive if n may or may not be a prime.
TEST (n)
1.  Find integers k, q, with k > 0, q odd, so that (n  1
    = 2kq);
2.  Select a random integer a, 1 < a < n  1;
3.  if aq mod n = 1 then return("inconclusive");
4.  for j = 0 to k  1 do
5.     if a2jq mod n  n  1 then return("inconclusive");
6.  return("composite");

Let us apply the test to the prime number n = 29. We have (n 1) = 28 = 22(7) = 2kq. First, let us try a = 10. We compute 107 mod 29 = 17, which is neither 1 nor 28, so we continue the test. The next calculation finds that (107)2 mod 29 = 28, and the test returns inconclusive (i.e., 29 may be prime). Let's try again with a = 2. We have the following calculations: 27 mod 29 = 12;214 mod 29 = 28; and the test again returns inconclusive. If we perform the test for all integers a in the range 1 through 28, we get the same inconclusive result, which is compatible with n being a prime number.
Now let us apply the test to the composite number n = 13 x 17 = 221. Then (n 1) = 220 = 22(55) = 2kq. Let us try a = 5. Then we have 555 mod 221 = 112, which is neither 1 nor 220; (555)2 mod 221 = 168. Because we have used all values of j (i.e., j = 0 andj = 1) in line 4 of the TEST algorithm, the test returns composite, indicating that 221 is definitely a composite number. But suppose we had selected a = 21. Then we have 2155 mod 221 = 200; (2155)2 mod 221 = 220; and the test returns inconclusive, indicating that 221 may be prime. In fact, of the 218 integers from 2 through 219, four of these will return an inconclusive result, namely 21, 47, 174, and 200.


Repeated Use of the Miller-Rabin Algorithm
How can we use the Miller-Rabin algorithm to determine with a high degree of confidence whether or not an integer is prime? It can be shown [KNUT98] that given an odd number n that is not prime and a randomly chosen integer, a with 1 < a < n 1, the probability that TEST will return inconclusive (i.e., fail to detect that n is not prime) is less than 1/4. Thus, if t different values of a are chosen, the probability that all of them will pass TEST (return inconclusive) for n is less than (1/4)t For example, for t = 10, the probability that a nonprime number will pass all ten tests is less than 106. Thus, for a sufficiently large value of t, we can be confident that n is prime if Miller's test always returns inconclusive.
This gives us a basis for determining whether an odd integer n is prime with a reasonable degree of confidence. The procedure is as follows: Repeatedly invoke TEST (n) using randomly chosen values for a. If, at any point, TEST returns composite, then n is determined to be nonprime. If TEST continues to return inconclusive for t tests, for a sufficiently large value of t, assume that n is prime.

A Deterministic Primality Algorithm

Prior to 2002, there was no known method of efficiently proving the primality of very large numbers. All of the algorithms in use, including the most popular (Miller-Rabin), produced a probabilistic result. In 2002, Agrawal, Kayal, and Saxena [AGRA02] developed a relatively simple deterministic algorithm that efficiently determines whether a given large number is a prime. The algorithm, known as the AKS algorithm, does not appear to be as efficient as the Miller-Rabin algorithm. Thus far, it has not supplanted this older, probabilistic technique [BORN03].

Distribution of Primes

It is worth noting how many numbers are likely to be rejected before a prime number is found using the Miller-Rabin test, or any other test for primality. A result from number theory, known as the prime number theorem, states that the primes near n are spaced on the average one every (ln n) integers. Thus, on average, one would have to test on the order of ln(n) integers before a prime is found. Because all even integers can be immediately rejected, the correct figure is 0.5 ln(n). For example, if a prime on the order of magnitude of 2200 were sought, then about 0.5 ln(2200) = 69 trials would be needed to find a prime. However, this figure is just an average. In some places along the number line, primes are closely packed, and in other places there are large gaps.
The two consecutive odd integers 1,000,000,000,061 and 1,000,000,000,063 are both prime. On the other hand, 1001! + 2,1001! + 3,..., 1001! + 1000, 1001! + 1001 is a sequence of 1000 consecutive composite integers.

Euler's Totient Function


Euler's Totient Function

Before presenting Euler's theorem, we need to introduce an important quantity in number theory, referred to as Euler's totient function and written f(n), defined as the number of positive integers less than n and relatively prime to n. By convention, f(1) = 1.
Determine f(37) and f(35).
Because 37 is prime, all of the positive integers from 1 through 36 are relatively prime to 37. Thus f(37) = 36.
To determine f(35), we list all of the positive integers less than 35 that are relatively prime to it:
1, 2, 3, 4, 6, 8, 9, 11, 12, 13, 16, 17, 18,
19, 22, 23, 24, 26, 27, 29, 31, 32, 33, 34.
There are 24 numbers on the list, so f(35) = 24.


Table 8.2 lists the first 30 values of f(n). The value f(1) is without meaning but is defined to have the value 1.
Table 8.2. Some Values of Euler's Totient Function f(n)
n
f(n)
1
1
2
1
3
2
4
2
5
4
6
2
7
6
8
4
9
6
10
4
11
10
12
4
13
12
14
6
15
8
16
8
17
16
18
6
19
18
20
8
21
12
22
10
23
22
24
8
25
20
26
12
27
18
28
12
29
28
30
8


It should be clear that for a prime number p,
f(p) = p 1
Now suppose that we have two prime numbers p and q, with p q. Then we can show that for n = pq,
f(n) = f(pq) = f(p) x f(q) = (p 1) x (q x 1)
To see that f(n) = f(p) x f(q), consider that the set of positive integers less that n is the set {1,..., (pq 1)}. The integers in this set that are not relatively prime to n are the set {p,2 p,..., (q 1)p} and the set {q,2q,..., (p 1)q} Accordingly,
f(n) = (pq 1) [(q 1) + (p 1)]
= pq (p + q) + 1
= (p 1) x (q 1)
= f(p) x f(q)
f(21) = f(3) x f(7) = (3 1) x (7 1) = 2 x 6 = 12
where the 12 integers are {1,2,4,5,8,10,11,13,16,17,19,20}


Euler's Theorem

Euler's theorem states that for every a and n that are relatively prime:

a = 3; n = 10; f(10) = 4
af(n) = 34 = 81 1(mod 10) = 1 (mod n)
a = 2; n = 11; f(11) = 10
af(n) = 210 = 1024 1(mod 11) = 1 (mod n)


Proof: Equation (8.4) is true if n is prime, because in that case f(n) = (n 1) and Fermat's theorem holds. However, it also holds for any integer n. Recall that f(n) is the number of positive integers less than n that are relatively prime to n. Consider the set of such integers, labeled as follows:
R {x1, x2,..., xf(n)}
That is, each element xi of R is a unique positive integer less than n with gcd(xi, n) = 1. Now multiply each element by a, modulo n:
S = {(ax1 mod n), (ax2 mod n),..., (axf(n) mod n)}
The set S is a permutation of R, by the following line of reasoning:
  1. Because a is relatively prime to n and xi is relatively prime to n, axi must also be relatively prime to n. Thus, all the members of S are integers that are less than n and that are relatively prime to n.
  2. There are no duplicates in S. Refer to Equation (4.3). If axi mod n = axj mod n then xi = xj.
Therefore,

This is the same line of reasoning applied to the proof of Fermat's theorem. As is the case for Fermat's theorem, an alternative form of the theorem is also useful:

Again, similar to the case with Fermat's theorem, the first form of Euler's theorem [Equation (8.4)] requires that a be relatively prime to n, but this form does not.

Euler's Totient Function


Euler's Totient Function

Before presenting Euler's theorem, we need to introduce an important quantity in number theory, referred to as Euler's totient function and written f(n), defined as the number of positive integers less than n and relatively prime to n. By convention, f(1) = 1.
Determine f(37) and f(35).
Because 37 is prime, all of the positive integers from 1 through 36 are relatively prime to 37. Thus f(37) = 36.
To determine f(35), we list all of the positive integers less than 35 that are relatively prime to it:
1, 2, 3, 4, 6, 8, 9, 11, 12, 13, 16, 17, 18,
19, 22, 23, 24, 26, 27, 29, 31, 32, 33, 34.
There are 24 numbers on the list, so f(35) = 24.


Table 8.2 lists the first 30 values of f(n). The value f(1) is without meaning but is defined to have the value 1.
Table 8.2. Some Values of Euler's Totient Function f(n)
n
f(n)
1
1
2
1
3
2
4
2
5
4
6
2
7
6
8
4
9
6
10
4
11
10
12
4
13
12
14
6
15
8
16
8
17
16
18
6
19
18
20
8
21
12
22
10
23
22
24
8
25
20
26
12
27
18
28
12
29
28
30
8


It should be clear that for a prime number p,
f(p) = p 1
Now suppose that we have two prime numbers p and q, with p q. Then we can show that for n = pq,
f(n) = f(pq) = f(p) x f(q) = (p 1) x (q x 1)
To see that f(n) = f(p) x f(q), consider that the set of positive integers less that n is the set {1,..., (pq 1)}. The integers in this set that are not relatively prime to n are the set {p,2 p,..., (q 1)p} and the set {q,2q,..., (p 1)q} Accordingly,
f(n) = (pq 1) [(q 1) + (p 1)]
= pq (p + q) + 1
= (p 1) x (q 1)
= f(p) x f(q)
f(21) = f(3) x f(7) = (3 1) x (7 1) = 2 x 6 = 12
where the 12 integers are {1,2,4,5,8,10,11,13,16,17,19,20}


Euler's Theorem

Euler's theorem states that for every a and n that are relatively prime:

a = 3; n = 10; f(10) = 4
af(n) = 34 = 81 1(mod 10) = 1 (mod n)
a = 2; n = 11; f(11) = 10
af(n) = 210 = 1024 1(mod 11) = 1 (mod n)


Proof: Equation (8.4) is true if n is prime, because in that case f(n) = (n 1) and Fermat's theorem holds. However, it also holds for any integer n. Recall that f(n) is the number of positive integers less than n that are relatively prime to n. Consider the set of such integers, labeled as follows:
R {x1, x2,..., xf(n)}
That is, each element xi of R is a unique positive integer less than n with gcd(xi, n) = 1. Now multiply each element by a, modulo n:
S = {(ax1 mod n), (ax2 mod n),..., (axf(n) mod n)}
The set S is a permutation of R, by the following line of reasoning:
  1. Because a is relatively prime to n and xi is relatively prime to n, axi must also be relatively prime to n. Thus, all the members of S are integers that are less than n and that are relatively prime to n.
  2. There are no duplicates in S. Refer to Equation (4.3). If axi mod n = axj mod n then xi = xj.
Therefore,

This is the same line of reasoning applied to the proof of Fermat's theorem. As is the case for Fermat's theorem, an alternative form of the theorem is also useful:

Again, similar to the case with Fermat's theorem, the first form of Euler's theorem [Equation (8.4)] requires that a be relatively prime to n, but this form does not.

Fermat's and Euler's Theorems


Fermat's and Euler's Theorems

Two theorems that play important roles in public-key cryptography are Fermat's theorem and Euler's theorem.

[Page 239]

Fermat's Theorem[4]

[4] This is sometimes referred to as Fermat's little theorem.
Fermat's theorem states the following: If p is prime and a is a positive integer not divisible by p, then
Equation 8-2

Proof: Consider the set of positive integers less than p:{1,2,..., p 1} and multiply each element by a, modulo p, to get the set X = {a mod p, 2a mod p, . . . (p 1)a mod p}. None of the elements of X is equal to zero because p does not divide a. Furthermore no two of the integers in X are equal. To see this, assume that ja ka(mod p) where 1 j < k p 1. Because a is relatively prime[5] to p, we can eliminate a from both sides of the equation [see Equation (4.3)] resulting in: j k(mode p). This last equality is impossible because j and k are both positive integers less than p. Therefore, we know that the (p 1) elements of X are all positive integers, with no two elements equal. We can conclude the X consists of the set of integers {1,2,..., p 1} in some order. Multiplying the numbers in both sets and taking the result mod p yields
[5] Recall from Chapter 4 that two numbers are relatively prime if they have no prime factors in common; that is, their only common divisor is 1. This is equivalent to saying that two numbers are relatively prime if their greatest common divisor is 1.
a x 2a x ... x (p 1) [(1 x 2 x ... x (p 1)](mode p)
ap1(p 1)! (p 1)!(mod p)
We can cancel the (p 1)! term because it is relatively prime to p [see Equation (4.3)]. This yields Equation (8.2).
a = 7, p = 19
72 = 49 11(mod 19)
74 121 7(mod 19)
78 49 7(mod 19)
716 121 7(mod 19)
ap1 = 718 = 716 x 72 7 x 11 1(mod 19)


An alternative form of Fermat's theorem is also useful: If p is prime and a is a positive integer, then
Equation 8-3

Note that the first form of the theorem [Equation (8.2)] requires that a be relatively prime to p, but this form does not.
p = 5,a = 3
ap = 35 = 243 3(mod 5) = a(mod p)
p = 5, a = 10
ap = 105 = 100000 10(mod 5) = 0(mod 5) = a(mod p)

Prime Numbers



Prime Numbers

[1] In this section, unless otherwise noted, we deal only with the nonnegative integers. The use of negative integers would introduce no essential differences.
A central concern of number theory is the study of prime numbers. Indeed, whole books have been written on the subject (e.g., [CRAN01], [RIBE96]). In this section we provide an overview relevant to the concerns of this book.
An integer p > 1 is a prime number if and only if its only divisors[2] are ± 1 and ±p. Prime numbers play a critical role in number theory and in the techniques discussed in this chapter. Table 8.1 shows the primes less than 2000. Note the way the primes are distributed. In particular, note the number of primes in each range of 100 numbers.

Equation 8-1

where p1 < p2 < ... < pt are prime numbers and where each is a positive integer. This is known as the fundamental theorem of arithmetic; a proof can be found in any text on number theory.
91
= 7 x 13
3600
= 24 x 32 x 52
11011
= 7 x 112 x 13


It is useful for what follows to express this another way. If P is the set of all prime numbers, then any positive integer a can be written uniquely in the following form:

The right-hand side is the product over all possible prime numbers p; for any particular value of a, most of the exponents ap will be 0.
The value of any given positive integer can be specified by simply listing all the nonzero exponents in the foregoing formulation.
The integer 12 is represented by {a2 = 2, a3 = 1}.
The integer 18 is represented by {a2 = 1, a3 = 2}.
The integer 91 is represented by {a7 = 2, a13 = 1}.


Multiplication of two numbers is equivalent to adding the corresponding exponents. Given a . Define k = ab We know that the integer k can be expressed as the product of powers of primes: . It follows that kp = ap + bp for all p P.

[Page 238]
k = 12 x 18 = (22 x 3) x (2 x 32) = 216
k2 = 2 + 1 = 3; k3 = 1 + 2 = 3
216 = 23 x 33 = 8 x 27


What does it mean, in terms of the prime factors of a and b, to say that a divides b? Any integer of the form can be divided only by an integer that is of a lesser or equal power of the same prime number, pj with j n. Thus, we can say the following:
Given , If a|b, then ap bp then for all p.
a
= 12;b = 36; 12|36
12
= 22 x 3; 36 = 22 x 32
a2
= 2 = b2
a3
= 1 2 = b3
Thus, the inequality ap bp is satisfied for all prime numbers.


It is easy to determine the greatest common divisor[3] of two positive integers if we express each integer as the product of primes.
[3] Recall from Chapter 4 that the greatest common divisor of integers a and b, expressed gcd(a, b), is an integer c that divides both a and b without remainder and that any divisor of a and b is a divisor of c.
300
= 22 x 31 x 52
18
= 21 x 32
gcd(18,300)
= 21 x 31 x 50 = 6


The following relationship always holds:
If k = gcd(a,b) then kp = min(ap, bp) for all p
Determining the prime factors of a large number is no easy task, so the preceding relationship does not directly lead to a practical method of calculating the greatest common divisor.

Prime Numbers



Prime Numbers

[1] In this section, unless otherwise noted, we deal only with the nonnegative integers. The use of negative integers would introduce no essential differences.
A central concern of number theory is the study of prime numbers. Indeed, whole books have been written on the subject (e.g., [CRAN01], [RIBE96]). In this section we provide an overview relevant to the concerns of this book.
An integer p > 1 is a prime number if and only if its only divisors[2] are ± 1 and ±p. Prime numbers play a critical role in number theory and in the techniques discussed in this chapter. Table 8.1 shows the primes less than 2000. Note the way the primes are distributed. In particular, note the number of primes in each range of 100 numbers.

Equation 8-1

where p1 < p2 < ... < pt are prime numbers and where each is a positive integer. This is known as the fundamental theorem of arithmetic; a proof can be found in any text on number theory.
91
= 7 x 13
3600
= 24 x 32 x 52
11011
= 7 x 112 x 13


It is useful for what follows to express this another way. If P is the set of all prime numbers, then any positive integer a can be written uniquely in the following form:

The right-hand side is the product over all possible prime numbers p; for any particular value of a, most of the exponents ap will be 0.
The value of any given positive integer can be specified by simply listing all the nonzero exponents in the foregoing formulation.
The integer 12 is represented by {a2 = 2, a3 = 1}.
The integer 18 is represented by {a2 = 1, a3 = 2}.
The integer 91 is represented by {a7 = 2, a13 = 1}.


Multiplication of two numbers is equivalent to adding the corresponding exponents. Given a . Define k = ab We know that the integer k can be expressed as the product of powers of primes: . It follows that kp = ap + bp for all p P.

[Page 238]
k = 12 x 18 = (22 x 3) x (2 x 32) = 216
k2 = 2 + 1 = 3; k3 = 1 + 2 = 3
216 = 23 x 33 = 8 x 27


What does it mean, in terms of the prime factors of a and b, to say that a divides b? Any integer of the form can be divided only by an integer that is of a lesser or equal power of the same prime number, pj with j n. Thus, we can say the following:
Given , If a|b, then ap bp then for all p.
a
= 12;b = 36; 12|36
12
= 22 x 3; 36 = 22 x 32
a2
= 2 = b2
a3
= 1 2 = b3
Thus, the inequality ap bp is satisfied for all prime numbers.


It is easy to determine the greatest common divisor[3] of two positive integers if we express each integer as the product of primes.
[3] Recall from Chapter 4 that the greatest common divisor of integers a and b, expressed gcd(a, b), is an integer c that divides both a and b without remainder and that any divisor of a and b is a divisor of c.
300
= 22 x 31 x 52
18
= 21 x 32
gcd(18,300)
= 21 x 31 x 50 = 6


The following relationship always holds:
If k = gcd(a,b) then kp = min(ap, bp) for all p
Determining the prime factors of a large number is no easy task, so the preceding relationship does not directly lead to a practical method of calculating the greatest common divisor.