I see other solutions to my question but none that help me.
I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.
Also, prompt the user again and again if anything other than a number is entered
Here's the code so far
When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1
function isPositive(num) {
var result;
if (num >= 0) {
result = true;
} else if (num < 0) {
result = false;
}
return result;
}
var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
alert(isPositive(num));
if (isNaN(num)) {
alert("No number entered. Try again");
num = parseInt(prompt("Enter a number"));
isPositive(num);
while (num != -1) {
alert(isPositive(num));
}
}
}
There's a few things wrong with your code, so here's a rewrite with comments:
function isPositive(num) {
// if something is true return true; else return false is redundant.
return num >= 0;
}
// when you want to keep doing something until a condition is met,
// particularly with user input, consider a while(true) loop:
var num;
while (true) {
num = prompt("Enter a number");
// check for null here
if (num === null) {
alert("No number entered. Try again.");
continue; // return to the start of the loop
}
num = parseInt(num, 10); // second argument is NOT optional
if (isNaN(num)) {
alert("Invalid number entered. Try again.");
continue;
}
// once we have a valid result...
break;
}
// the loop will continue forever until the `break` is reached. Once here...
alert(isPositive(num));
Math.sign(number)
which returns either a 1, -1 or 0
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
The number 0 is neither positive, nor negative! :P
function isPositive(num)
{
if(num < 0)
return false;
else
return true;
}
Or a simple way,
function isPositive(num)
{
return (num > 0);
}
You are testing if it isn't -1. Try this:
if(num < 0){
...IS NEGATIVE...
}else{
...IS POSITIVE...
}
This checks if it is less than or greater than 0.
Related
I want to write a function that finds the next largest palindrome for a given positive integer. For example:
Input: 2
Output: 3 (every single digit integer is a palindrome)
Input: 180
Output: 181
Input: 17
Output: 22
My try
function nextPalindrome(num) {
let input = num;
let numToStringArray = input.toString().split('');
let reversedArray = numToStringArray.reverse();
if (numToStringArray.length < 2) {
return Number(numToStringArray) + 1;
} else {
while (numToStringArray !== reversedArray) {
// numToStringArray = num.toString().split('');
// reversedArray = numToStringArray.reverse();
num += 1;
}
return numToStringArray.join('');
}
}
As a beginner, I thought that the numToStringArray would constantly increment by 1 and check for whether the while-statement is true.
Unfortunately it doesn't. I commented out two lines in the while-statement because they seemed somewhat redundant to me. Thanks to everyone reading or even helping me out!
The reason your code doesn't work is because you don't have any code updating the conditions of your while loop. So if you enter it once, it will loop indefinitely. You need to do something inside of the while loop that might make the condition false the next time through the loop, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else {
while(num !== getReverse(num)) {
num += 1;
}
return num;
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));
You could also solve this pretty cleanly using recursion, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else if(num === getReverse(num)) {
return num;
}
else {
// if not the same, recurse with n + 1
return nextPalindrome(num + 1)
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));
I have two textbox prompts that I need to validate to only accept numbers or an empty field and if you input anything else than numbers or the empty field the run button should be disabled.
oCR = cognos.Report.getReport('_THIS_');
var prompts;
var f1 = oCR.prompt.getControlByName('Prompt1');
var f2 = oCR.prompt.getControlByName('Prompt2');
prompts = [f1,f2];
for (var i=0; i < prompts.length; i++) {
prompts[i].setValidator(validate);
}
function validate() {
var result = false;
for (var i=0; i < prompts.length; i++) {
var x = prompts[i].getValues();
if(x.length == 0) { result = true;}
if(x.length == 1 && x['use'] == " ") {result = true};
if(x.length > 0) {
var sValue = x['use'];
var codeFormat = new RegExp("^\\d+$")
if(codeFormat.test(sValue)) {
result=true;
}
}
}
if(result == true) {
getLink("Runreport").css("background-color", "#005FA5").css("border-color", "#005FA5").css("pointer-events","auto");
} else {
getLink("Runreport").css("background-color", "#dddddd").css("border-color", "#cccccc").css("pointer-events","none");
}
return result;
}
This doesn't really work the way I want. Because now it checks if both prompts checks for true. But if one prompt is true and the other is false it should be false not true. Anyone have an idea how to resolve this?
Here's your validate function simplified and restructured a bit:
function validate(values) {
var result = true,currentresult = true,x;
if (values.length > 0) {
if (isNaN(values[0].use)) {
currentresult = false;
}
}
for (var i=0; i < prompts.length; i++) {
x = prompts[i].getValue();
if (x.length > 0) {
if (isNaN(x)) {
result = false;
break;
}
}
if (prompts[i] != this) {
prompts[i].checkData();
}
}
if (result) {
getLink("Runreport").css("background-color", "#005FA5").css("border-color", "#005FA5").css("pointer-events","auto");
} else {
getLink("Runreport").css("background-color", "#dddddd").css("border-color", "#cccccc").css("pointer-events","none");
}
return currentresult;
}
Since you want the failure of either of your two prompts to cause invalidation, we start by setting the result to true. We then look for the special case that a prompt is invalidated. That special case results when the length of the prompt is not 0 (outer if), and the contents of the prompt is not a number (inner if). I used the isNaN() function because it will return true if the passed in value is a not a number and false if the value is a number. If isNan() returns true, then we set the result to false and break out of the for loop. The result is that if any of the prompts returns false, the whole result will be false.
For some more fun with text prompt validation, check out my advanced techniques Cognos Prompt Numeric Range Validation which demonstrates some other ways to do multi-prompt validation and Multi-prompt Validation which shows how to validate multiple prompts as a group.
I am currently stuck with this challenge: https://www.freecodecamp.org/challenges/sum-all-primes
I am trying to sum all the prime numbers from 0 to 10
I have a function to check if the number is a prime number. If I pass 9 it returns false which is good.
However when I am decrementing from 10 with a while loop and it passes 9 into the function it seems to be returning true and adding it to my sum. As a result I get the result of 24 when the sum of all the prime numbers in 10 is 17! This is because it is adding 9 as a prime number.
Here is my code, I must be missing something obviouse here but I can figure it out!
function sumPrimes(num) {
function isPrime() {
for (var i = 2; i <= num; i++) {
if (num % i === 0) {
return false;
}
return num !== 1;
}
}
// alert(isPrime(9)); // returns false
var count = 0;
while (num >= 0) {
if (isPrime(num)) {
count += num;
console.log(count);
}
num--;
}
console.log(count);
}
sumPrimes(10);
Firstly you need to return true from isPrime() if no number less than num divides the number so remove return num !== 1; from inside the for loop and add return true after the loop. Also you are running the loop in function isPrime() till the number num, since every number is divisible by itself, function will return false for every number, change for loop condition to i<num. Also note that 1 is not a prime number so you don't need to add it in the sum.
function sumPrimes(num) {
function isPrime(num){
if(num === 1 ) //since 1 is neither prime nor composite.
return false;
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
// alert(isPrime(9)); // returns false
var count = 0;
while (num >= 0) {
if (isPrime(num)) {
count += num;
alert(count);
}
num--;
}
console.log(count);
}
sumPrimes(10);
try to modify the following code snippet
function isPrime() {
for (var i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {return false;}
}
return true;
}
Using Math.sqrt(num) as an upper limit will improve time complexity and speed up the computation for large numbers (see my online Prime Numbers Calculator up to 18 digits implementing this algo with some additional optimization: http://examn8.com/Primes.aspx )
Hope this may help.
How would you write a function that determines if the two numbers a user enters is both odd and returns a boolean value that is true if both numbers are odd? I already know how to write a function that determines if the two numbers a user enters is even or not.
Try:
function bothOdd(num1, num2) {
if (num1 % 2 == 1 && num2 % 2 == 1) {
return true;
}
return false;
}
window.alert(bothOdd(1, 2));
window.alert(bothOdd(1, 1));
That pretty easy and simple
numbersOdd(1,2); // return false
numbersOdd(14, 222); // return true;
function numbersOdd(n1, n2) {
return n1%2 === 1 && n2%2 === 1;
}
i have two variable i am getting through two prompts. One is startNum the other is rangeNum. I am trying to error catch it so that if they are not positive numbers, it will reprompt the user until a postive value is given. Currently i have this working by running an isnan for each vaiable, but im wondering if I can just have one function that checks for both prompts whether the number entered is positive, and also if not, it will reprompt the correct prompt to the user. Thanks in advance for any help/answers.
function isPosNum() {
startNum = parseInt(prompt("Please enter a positive starting value"));
if (isNaN(startNum)) {
return NaN;
} else if (startNum < 0) {
console.log('failed');
alert('That is not a positive number. Please try again and enter a positive number.');
return "negative";
isPosNum();
} else if ( startNum > 0) {
console.log('worked');
//push initial value to the array
numArray.push(startNum);
//enterRange();
return "positive";
} else {
return "zero";
}
function enterRange() {
rangeNum = parseInt(prompt("Please enter a number to determine the range of values."));
if (isNaN(rangeNum)) {
return NaN;
} else if (rangeNum < 0) {
console.log('failed');
alert('That is not a positive number. Please try again and enter a positive number.');
return "negative";
enterRange();
} else if ( rangeNum > 0) {
console.log('worked');
//push initial value to the array
//collatz();
return "positive";
} else {
return "zero";
}
}
}
I was able to get the code working thanks to deamentiaemundi's answer. Here is my final code for those who wish to see.
function getStartNum(){
startNum = parseInt(prompt('Please enter a starting number greater than 0.'));
if(!isPosNum(startNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getStartNum();
} else {
getRangeNum();
}
}
function getRangeNum(){
rangeNum = parseInt(prompt('Please enter a range value greater than 0'));
if(!isPosNum(rangeNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getRangeNum();
}
// and so on
}
function isPosNum( number ) {
if (isNaN( number )) {
return false;
} else if (number < 0) {
return false;
} else if (number == 0) {
return false;
} else {
return true;
}
}
Make a function checkRange(number) which takes the number as an argument and returns either true or false depending on that number.
The second function is the one with the prompts in it.
function getNumbers(){
startNum = parseInt(prompt('Please enter a number'));
if(!checkRange(startNum)){
alert("error!");
getNumbers();
}s
rangeNum = parseInt(prompt('Please enter a range'));
if(!checkRange(rangeNum)){
alert("error!");
getNumbers();
}
// and so on
}