Create a Windows Forms application that has the following: Define a function nam
ID: 3714430 • Letter: C
Question
Create a Windows Forms application that has the following:
Define a function named IsPositive, which has one parameter as Integer. If the number in the parameter is positive (>= 0) the function returns True, otherwise it returns False.
A button showing the text Factorial. When clicked this button uses a function named Factorial passing it a number typed in a textbox named NumEntrytxt. Then check the return value of the Factorial function, using IsPositive. If it is positive then show the factorial value in textbox named Resulttxt. Otherwise show the message "Data entered has no defined factorial".
A button showing the text Prime ?.When clicked this button uses a function named IsPrime passing it a number typed in a textbox named NumEntrytxt, then it shows the result in a textbox named Resulttxt. If the function returns True, the result should be "X is Prime", otherwise show "X is not Prime", where X is the actual number passed to the function.
Write the function definition of Factorial, which has one integer parameter and uses the IsPositive function to check if the number passed is positive, then it returns the factorial of that number (code to calculate factorial is in the book in an earlier chapter). If the number is not positive, Factorial returns -1 (meaning there is an error).
Write the function definition of IsPrime, which has one integer parameter and uses the IsPositive function to check if the number passed is positive, then it returns True if the number pass is indeed a prime number, otherwise return False. Code to check if a number is a prime number, is in the book in an earlier chapter.
Explanation / Answer
<html>
<body>
<input type ="number" id="num" />
<button>check for prime</button>
<button>check for factoril</button>
<p id="resultPrimeText"></p>
<p id="resultText"></p>
<script>
function checkFactorial(){
var number = document.getElementById("num").value;
if(isPositive(number)){
document.getElementById("resultText").innerHTML = factorial(number);
}else{
document.getElementById("resultText").innerHTML = "Negative number";
}
}
function factorial(n) {
if (n === 0) {
return 1;
}
// This is it! Recursion!!
return n * factorial(n - 1);
}
function isPositive(num) {
if(num <0){
return false;
}else{
return true;
}
}
function isPrime(n){
if (n===1)
{
return false;
}
else if(n === 2)
{
return true;
}else
{
for(var y = 2; y < n; y++)
{
if(n % y === 0)
{
return false;
}
}
return true;
}
}
function checkPrime() {
var number = document.getElementById("num").value;
if(isPositive(number)){
if(isPrime(number)){
document.getElementById("resultPrimeText").innerHTML = "prime number";
}else{
document.getElementById("resultPrimeText").innerHTML = "Negative number";
}
}else{
document.getElementById("resultPrimeText").innerHTML = "Negative number";
}
}
</script>
</body>
</html>