Design a HTML having a text box and four buttons viz Factorial, Fibonacci, Prime, and Palindrome. When a button is pressed an appropriate javascript function should be called to display
- Factorial of that number
- Fibonacci series up to that number
- Prime numbers up to that number
- Is it palindrome or not
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JS Functions</title>
<script type="text/javascript">
var result;
//Validating input data
function validate() {
var num = document.ip.num.value;
var re_num = new RegExp("^[0-9]+$","g");
if(num.match(re_num)){
return parseInt(num);
}else{
return false;
}
}
//Find factorial of given number
function factorial(){
var val = validate();
if(val){
result = 1;
for (var i=1; i<=val; i++) {
result *= i;
}
document.getElementById('result').innerHTML="Factorial of given number is "+result;
}else{
window.alert("Invalid input");
}
}
//Find fibonacci within range
function fibonacci(){
var val = validate();
if(val){
result = "Fibonacci Sequence is<br>0 1";
var n1=0,n2=1,n3=n1+n2;
while(n3<=val){
result = result+" "+n3;
n1 = n2;
n2 = n3;
n3 = n1+n2;
}
document.getElementById('result').innerHTML=result;
}else{
window.alert("Invalid input");
}
}
//Find primes within range
function prime() {
var i,j;
var val = validate();
if(val){
result = "Prime in given range<br>";
for(i=2;i<=val;i++){
for(j=2;j<=parseInt(i/2);j++){
if(i%j==0)
break;
}
if(j>parseInt(i/2))
result = result+" "+i;
}
document.getElementById('result').innerHTML=result;
}else{
window.alert("Invalid input");
}
}
//Find whether number is palindrome or not
function palindrome(){
var val = validate();
if(val){
var rev=0,temp = val;
while(temp!=0){
rev = rev*10+temp%10;
temp=parseInt(temp/10);
}
if(rev==val){
document.getElementById('result').innerHTML="Given number is Palindrome";
}else{
document.getElementById('result').innerHTML="Given number is not Palindrome";
}
}else{
window.alert("Invalid input");
}
}
</script>
</head>
<body>
<center>
<form name="ip">
<input type="text" name="num" placeholder="Enter Number" /><br><br>
<input type="button" value="Factorial" onclick="factorial()" />
<input type="button" value="Fibonacci" onclick="fibonacci()" />
<input type="button" value="Prime" onclick="prime()" />
<input type="button" value="Palindrome" onclick="palindrome()" />
</form><br>
<div id="result" style="color: green;font-weight: bold;"></div>
</center>
</body>
</html>