I'm trying to write this program to find prime numbers. I have the basics of it down, except that no matter what number I put in, it returns as NOT prime. I've been messing with this for way too long and cannot figure out what it is. Is it in my "if" statement or my isPrime function? Please help, and thank you!
var number = 0;
function main()
{
number = parseInt(prompt("Please Enter a Number to Determine Whether or Not it is Prime:", "Enter a Number"));
while(isNaN(number) === true)
{ alert("You Entered an Invalid Number. Please Reenter");
number = parseInt(prompt("Please Enter a Number to Determine Whether or Not it is Prime:", "Enter a Number"));
}
isPrime(number);
if(prime = false)
{ alert("The number " + number + " is a Prime Number!"); }
else
{ alert("The number " + number + " is NOT a Prime Number!"); }
}
/*------------------------------------------------------*/
function isPrime(number)
{
if(number < 2)
{return false;}
var prime = false;
for(var i = 2; i <= Math.sqrt(number); i++)
{ if(number % i == 0)
{prime = true;}
}
return prime;
}
if (prime = false)
You just assigned prime to false.
You don't want to do that.
By contrast, you do want to assign it to the result of your function.
Replace:
if(prime = false)
not only because you're using assignment instead of comparison, but because prime is not defined (it's not going to return/create a global variable prime from that function call).
Replace it with:
if (!isPrime(number)) {
Now this doesn't use a variable to store the result of the isPrime call, but uses the call directly. If you need this result in more than one place, then it would be a good idea to assign it to a variable:
var prime = isPrime(number);
and then do the rest of your code:
if (prime == false)...
isPrime(number);
leaves no variable assigned. Therefore prime is never assigned in your test and unassigned variables are treated as false as far as boolean expressions are concerned.
It should be
var prime = isPrime(number);
You're also doing an assignment where you meant to do a comparison.
if(prime = false)
should be
if(prime === false)
Tip: If you're doing these kinds of tests, it's usually a good idea to put the thing that can't be changed by assignment on the left (function call, constant, etc). That way if you accidentally put = instead of == or === the script will fail with an error.
if(false === prime)
If you accidentally type
if (false = prime)
you'll get
ReferenceError: invalid assignment left-hand side
which is obvious and easy to debug.
As this is a simple boolean switch, a simple "is not true" check is fine.
if (!prime)
Actually their are only 2 small logic failure.
You define "prime" inside your function isPrime() - hence you cannot use it outside your function.
You try to do if(prime = false) which assigns the value false to "prime" whick does nothing for your if except breaking it.
You need to define the variable outside hence use your prime = isPrime()
Also you do not need to check against "false" which by any means does not really make sense their. "true == false" ? just skip that ans ask for if(prime) which is true or false.
Alternativly you can call your funtion directily in the if condition like:
if(isPrime(number)){....
it then automaticly checks the return value.
Related
I am slightly confused on the logical NOT operator in Javascript (!). From my understanding, this is mainly used to "inverse" a boolean value. For example, if an expected output of a boolean is true, putting this in front would turn it to false, and vice versa.
In my below code, I created a function allowing user to input a lower and upper integer, and the function would generate a random number between this range. If, however, the user inputs a string instead of an integer, it will prompt the user to enter an integer instead.
I am using isNaN to check if user's input is an integer, and using logical NOT operator in front of it to inverse the result.
In my if condition, if I check isNaN for lower && isNaN for upper are both not a number, this program seems to work correctly. However, if I use ||, it doesn't work as expected, as shown in my code below.
Why is this so? By using OR operator, I am saying if either upper or lower is NaN, then prompt the user to enter a valid integer. Why is it a && and not a || when only one condition needs to be true?
const getNumber = function(lower, upper) {
if ( !isNaN(lower) || !isNaN(upper) ) {
const number = Math.floor(Math.random() * (upper - lower + 1)) + lower;
return number;
} else {
alert("Please enter a valid integer.");
}
};
// Call the function and pass it different values
console.log( getNumber('six',5) );
It's not the ! operator that's the problem, it's ||. if ( !isNaN(lower) || !isNaN(upper) ) { says (roughly) "if lower is a number or upper is a number". But you don't wan to say "or" there, because you want them both to be numbers.
So either use use && (and):
if ( !isNaN(lower) && !isNaN(upper) ) {
// −−−−−−−−−−−−−−−−^^
const number = Math.floor(Math.random() * (upper - lower + 1)) + lower;
return number;
} else {
alert("Please enter a valid integer.");
}
or reverse the content of your if and else blocks and use || without !:
if ( isNaN(lower) || isNaN(upper) ) {
alert("Please enter a valid integer.");
} else {
const number = Math.floor(Math.random() * (upper - lower + 1)) + lower;
return number;
}
Side note: You're using implicit string-to-number parsing in your code. I recommend doing it on purpose. My answer here goes into your various options for parsing numbers and their pros and cons.
By using OR, you are checking that at least one value should not be NaN.
let a = !isNaN(lower);
let b = !isNaN(upper);
a and b can be either true or false. When you use ||, you are telling that at least one of this values should be true. If you check Truth table, you will see that OR will be true for this combitations of a and b:
a == true, b == true
a == false, b == true
a == true, b == false
What you want is to check that a == true and b == true simultaneously - so you have to use AND (&&) which will evaluate to true if and only if a == true and b == true.
My loop is not quitting when i enter 10. Please help me.
let getGuessess = function(){
let guessedNum = null;
while(guessedNum !== 10){
guessedNum = prompt(`enter number $`);
if(guessedNum === "quit"){
break;
}
}
}
getGuessess();
Change from !== to !=. You're doing a strict equality check on 10 vs '10'.
or !== '10'
Maybe these links can help:
https://www.w3schools.com/js/js_comparisons.asp
I see there that:
!== means not equal value or not equal type
https://www.w3schools.com/jsref/met_win_prompt.asp
And here that, for the prompt function:
Return Value: A String.
I think that it doesn't work because you are comparing a string and an int, they are different types, so your comparison returns False even if you enter 10.
If the user enters nothing in the prompt box then also it is showing "The num is prime", I have put validation below. Also if I enter "1" in prompt box, it is still showing "The num is prime".
var Num = prompt("Enter the Number");
var flag = 0;
if (isNaN(Num)) {
alert("please enter valid number");
}
for (var i = 2; i < Num; i++) {
if (Num % 2 === 0) {
flag = 1;
break;
}
}
if (flag === 0) {
alert("The num is prime");
}
else if (flag === 1) {
alert("The num is not prime");
}
Annoyingly, isNaN("") returns false, as if "" were a number. To fix the problem with the empty prompt, you're gonna need to check that Num.length > 0
The isNaN function is not intended to be used to check whether or not something can be interpreted as a number. It's intended to check if the provided value is the specific NaN value. My suggestion would be to attempt to convert the prompted string into a number and see if that conversion was successful.
var Num = parseInt(prompt("Enter the Number"), 10);
if(Number.isNaN(Num)) {
alert("please enter valid number");
}
Please note: this will not ensure that all provided values will be valid. For example, parseInt("ABC123") will return NaN as expected, but parseInt("123ABC") will return 123 and ignore the subsequent "ABC".
Regarding the issue with 1s, the code you have provided appears to mark all odd numbers as prime. Assuming you have written the part that determines whether or not an odd number is prime, you could have a special case to say "if the number is 1, it's not prime." That's because for many purposes, 1 acts like a prime number. Obviously, it's not the most elegant solution, but... it works.
I wrote this program out in plain code but I don't know Javascript well enough to get all the syntax right. I am a beginning programming please help me with corrections to my code. It is currently not running at all. We are still going over loops and it's really giving me trouble. This is for a college class. (I know this isn't formatted properly that's why i'm asking for help)
function main() {
alert("Welcome to the program");
var fatGrams = getFatGrams(fatGrams);
var calories = getCalories(fatGrams,calories);
var percentage = caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
Errors in your code :
The function keyword is not needed to call a function. Remove the keyword function before calling a function and simply call the function as getFatGrams(fatGrams);
You are not passing parameters to function caloriesPercentage. Change it to caloriesPercentage(fatGrams,calories);
The expression for a while loop should be enclosed in paranthesis as while(fatGrams < 0).
The OR should be written as ||.
Use + to concatenate 2 string (Or a string and a variable)
"The amount of calories that come from fat is, " + percentage
The expression for an while should also be enclosed in paranthesis as if(percentage < 0.3) and no then is needed. The curly brackets of if should be closed before else.
if(percentage < 0.3){
alert("The food is low in fat.");
}
else {
alert("The food is not too low in fat.");
}
assign value from prompt to variable as
fatGrams = prompt("Enter the new number of fat grams.");
Your final code should look like this :
function main() {
alert("Welcome to the program");
var fatGrams;
var calories;
var percentage;
getFatGrams(fatGrams);
getCalories(fatGrams,calories);
caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
welcome to the wonderful world of programming!
It looks like you are getting the basics down, let me explain some of the issues you are having with JavaScript. I'm going to use some big words (as will many other experienced developers so get used to them!).
Function Declaration vs Function Invocation
The very first issue I see with your main() function is a confusion about when to use the function keyword in JavaScript. You only need to use function when you are declaring a function, or in other words when you want to "create a new function." When you declare something, you are creating it, and in JavaScript the function keyword is how you declare (aka create) a Function. Here is an example of creating a "named function" in javascript.
function addTwo( number ) {
return number + 2;
}
That right there is a "named function" declaration. On a side note, you can also create functions as "expressions" (which would be called a "function expression"). That would look like this
var addThree = function( number ) {
return number + 3;
};
Note that in both cases we are creating a function with the function keyword.
When you want to use a function, you "invoke" it. This is also referred to as "calling" a function. To call (aka invoke) a function you simply write the function name with parenthesis behind it, passing in any arguments. Function invocation works the same for both named functions and function expressions. So we could invoke the two functions above like so
var four = addTwo( 2 );
var five = addThree( 2 );
Simply put, only use the function keyword to make functions. To call or use a function just put ( argument, otherArg ) at the end of the function name.
Branching Statements
The next thing I see is that you're missing some parenthesis! JavaScript has a C style syntax so that means you need to put parenthesis around expressions for if, else if, and switch statements. Those keywords I listed are what we call Branching Statements. They allow you to conditionally execute code based on some true or false value, as opposed to Looping Statements that allow you to repeat code based on a true or false value. The structure for an if .. else branching statement in JavaScript is as follows.
if ( number % 2 === 0 ) {
number *= 2;
} else if ( number % 3 === 0 ) {
number *= 3;
} else {
number += 5;
}
For both if and else if you need to provide an "expression" to branch around. An else statement is always executed if none of the if or else if expressions evaluated to true. The else clause is not required so if you don't have any code in your else block you can just remove it! It is perfectly fine to have a single if statement like this in your code
if ( needsCleanup ) {
doCleanup();
}
Of course it would be ok to have an else if clause and no else clause, the else is always optional. But remember the else clause never has an expression so you should never write () after a simple else.
Looping Statements
Looping is a big concept that takes a while to master so don't get frustrated or discouraged! In JavaScript we have for, while and do while loops. Just like if statements looping statements need an expression, but in this case they need it to know when to stop looping. I'm not going to cover do while loops because they are rarely used and can be confusing when just starting out. Simply put, looping statements say: "keep executing this code block until the expression is false." I find it easiest to illustrate this with a for loop. For loops are a great way to run a code block a specific number of times. Let's look at an example that adds all the numbers from 1 to 10 with a for loop.
var sum = 0;
for ( var i = 1 ; i <= 10 ; i++ ) {
sum += i;
}
// sum will be 55
// i will be 11
A for loop has three expression separated by ;. The first is for initialization and is only executed before the loop starts (the var i = 1 part). The second is the condition that is checked before each iteration. The last is an increment operation that is executed at the end of every loop execution. If we were to re-write this for loop as a while look it would look like this...
var sum = 0;
var i = 1;
while ( i <= 10 ) {
sum += i;
i++;
}
So you can see the var i = 1 happens before the loop starts. The i <= 10 happens before each time the loop runs its body (the part in the {}). And the i++ happens at the end of the loop before it checks i <= 10 to see if it should keep looping.
String Concatenation
String concatenation is the process of putting two strings together. In JavaScript the + operator does double duty as addition 1 + 1 and string concatenation 'hello' + ' world'. So when you want to put two strings together you simply add them! If the strings are in variables then you can just "add" them together...
var salutation = 'Hello';
var name = 'Kylie';
var greeting = salutation + ', ' + name;
// greeting will be "Hello, Kylie"
I hope that clears some things up, if you have any questions please let me know!
Because this IS for a class I am NOT going to give you the answers but instead point out the issues.
Calling a function in Javascript and return a value:
var myvalue = myFunction();
You have function... in your main and need to fix that.
Some functions just return values and thus calling them needs no parameter (like above) others need parameters for the inputs which you have done.
Prompt returns a value and you need to capture that value:
var myinputvalue = prompt("enter value");
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Conditionls need to be wrapped in parenthesis when using while, if etc.
while (mything < 0){ Reference; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
" OR " in a conditional is represented by || and an AND by &&
NOTE: You can use some on-line tools to work out some of the issues for example paste your code into http://jshint.com/ and it will tell you many of the syntax issues.
I'm a student creating a 3-guess game with JavaScript. My game doesn't work properly, I believe Math.random is generating a new number at every stage of the game. I would be most grateful if somebody helps me define a single number for the variable randomNumber.
Here's the JavaScript:
function game()
{
var randomNumber = Math.floor(Math.random()*11);
var userGuess = prompt ("Guess what number I'm thinking of? (It's between 0 & 10)");
if (userGuess === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
var userGuess2 = prompt ("Dohhh! You got it wrong. You have 2 more chances.");
}
if (userGuess2 === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
var userGuess3 = prompt ("Dohhh! You got it wrong. You have 1 more chance.");
}
if (userGuess3 === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
alert ("Bad luck. The number was: " + randomNumber);
}
}
prompt returns a string. You are using the strict equality operator, ===, to compare strings with numbers. They will never be equal.
Use the abstract equality operator, ==, or convert the strings to numbers before comparing with the strict equality operator.
Also, your function should probably return after a correct guess, rather than prompting for more guesses.
Here's a suggestion for a cleaned-up version of your code:
function playGame(guesses)
{
// By default, give the player 3 guesses.
guesses = guesses || 3;
var randomNumber = Math.floor(Math.random()*11);
var userGuess = prompt("Guess what number I'm thinking of? (It's between 0 & 10)");
// Repeat the following logic whenever the user guesses incorrectly.
while (userGuess !== randomNumber.toString())
{
--guesses;
if (guesses === 0)
{
alert("Bad luck. The number was: " + randomNumber);
return false;
}
userGuess = prompt("Dohhh! You got it wrong. You have " + guesses + " more chance(s).");
}
alert("Good Guess, you must be psychic!");
return true;
}
Notice that it's now more flexible (you can give the user a configurable number of guesses) while also reducing code duplication: instead of repeating the same block of logic (with small differences), there is really just one bit of logic that can be repeated as many times as you like.