An algorithm is like a recipe, it provides the steps which are to be taken to solve a problem. Algorithms do not have to be implemented on a computer but obviously we are concerned with ones which are.
An algorithm for finding numbers in the Fibonacci sequence might be:
Here is the code with some key items left out and replaced with '###' - can you restore the working version of the program?
function fib(){
var a=###; var b=###;
var astr=### + ' ' + ### + ' '; //initialise output string
document.fibform.fibout.value=###; //output first 2 numbers
if ((document.fibform.numfib.value>0) && (document.fibform.numfib.value<=25)){
for (i=0;i<document.fibform.numfib.value-2;i++) {
var c=###;
a=###; b=###;
astr+=###+' ';
document.fibform.fibout.value=###;
}
}
else {document.fibform.fibout.value='number out ###';}
}
Here is a working version:
Here is the code with key parts replaced with '###' - can you restore it?
function primefind(){
var astr='';document.primesform.primesout.value=astr;
var p=document.primesform.primetest.value; //an alias for a long name
### prime;
var j=###;
if ((p>0) && (p<=65536)){
prime=###;
for (j=###;j<= Math.floor(Math.###(p));j++){
if (p % j == ###) {prime=###;break}}
if (###==###) {astr+=p+' is prime';}
else {###+=p+' is not prime. It divides by '+ ###+'.'};
document.primesform.primesout.value=astr;}
else {document.primesform.primesout.value='number out of range, try again';}
}
Can you extend the code to output a list of prime numbers?
Here is the form from which the function is called:<FORM NAME="primesform"><TABLE BORDER=0>
<TR><TD><FONT FACE="Arial" SIZE=-1>Enter a number to see if it's prime: </FONT>
<INPUT TYPE="text" NAME="primetest" SIZE=10 MAXLENGTH=10>
<INPUT TYPE="button" NAME="primesin" VALUE="Test Your Number!" onClick="primefind()">
<INPUT TYPE="reset"<>/TD></TR>
<TD><INPUT TYPE="text" NAME="primesout" SIZE=45 MAXLENGTH=45></TD>
</TR></TABLE></FORM>
Return to JavaScript Menu