Prime Number Function in Javascript ...multiple statements - javascript

So I'm tasked with making program that can tell whether a number is prime or not. I want to solve this problem using a multiple if-statement. The one that I came up with is awkward. So i just want some feedback on how to make it better.:
function primenumber(num) {
if (num / num === 1 && num % 2 !== = 0 || num % 3 !== = 0 | num % 5 !== = 0 | num % 7 !== = 0) {
return true;
} else {
return false
}
}
I figured these numbers are the lowest common denominators. So a number is prime if these numbers don't divide evenly into it. Any feedback is greatly appreciated. Keep in mind that I am new to Javascript.

I figured it out:
If((num === 1) || (num === 2) || (num === 3) || (num === 5) || (num === 7))
{ return true;
}
If((num%2===0) || (num%3===0) || (num%5===0) || (num%7===0)){
return false;}
}
return true;
}
It may not be the most sophisticated coding but it's mine and it works perfectly.. at least according to coderbyte

Related

powerofTwo algorithm solution

Below is my algo to check if number is a power of two. When I run this algo in test case "2" the answer is false. I want to know why it behaves this way ?
var isPowerOfTwo = function(n) {
if(n === 1){
console.log("i came here");
return true;
}
if(n === 0){
return false;
}
if(n%2 === 0){
console.log(n);
n=n/2;
console.log(n);
isPowerOfTwo(n);
}
if(n%2 === 1){
return false;
}
};
You're not returning the recursive call, and you're also changing n before the tests have finished - if n / 2 resolves to 1 then your reassignment of n will result in the bottom if statement running. Use else instead, and don't reassign n, simply pass n / 2 to the recursive call:
var isPowerOfTwo = function(n) {
if (n === 1) return true;
if (n === 0) return false;
if (n % 2 === 0) return isPowerOfTwo(n / 2);
else return false;
};
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Your if (n%2 === 1) return false; condition could result in another bug: what if the initial n was not an integer? Then the function would call itself forever, resulting in an overflow.
Because 1 % 2 === 1
The "problem" is that in the third if you are changing the value of n and not returning any value so it will enter the last if too.
As mentioned, you don't return any value in the 3rd if statement, hence you always get false for values greater than 1 as it will execute the 4th statement too.
In addition to the given answers, here is an interesting solution (initially by Jaromanda X), which I expanded so it deals with if a non-number is passed as a value.
Try cast to a number
const isPowerOfTwo = n => Number(n).toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Check the type
const isPowerOfTwo = n => typeof n === 'number' && n.toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
I think you just need to return an actual value from the n % 2 === 0 branch of your function:
var isPowerOfTwo = function(n) {
if (n === 1) {
console.log("i came here");
return true;
}
else if (n === 0) {
return false;
}
else if (n % 2 === 0) {
console.log(n);
n = n / 2;
console.log(n);
return isPowerOfTwo(n);
}
else { // no need for an if here
return false;
}
};
Note that in the final else we do not need to check anything, because we have already ascertained the number is not a multiple of 2.
Javascript one-liner solution
For any power of 2 (n & n - 1) will return 0. Simple bit-wise operators
isPowerOfTwo = n => !(n & n - 1)
The above function will return true for 0, which is not a power of 2. For that
isPowerOfTwo = n => (n != 0) && !(n & n - 1)

javascript - Finding remainder of integer not working

I want to find (using JS) the greatest 3-digit number that
leaves a remainder of 1 when divided by 2
leaves a remainder of 2 when divided by 3
leaves a remainder of 3 when divided by 4
leaves a remainder of 4 when divided by 5
This is my code:
var bool = false;
for(var i = 999; bool == true; i = (i - 1)) {
if(i % 2 == 1 && i % 3 == 2 && i % 4 == 3 && i % 5 == 4) {
bool = true;
alert(i);
}
}
But it did not work (somehow there was no error messages, and the alert did not show up). So how can I find that 3-digit number? Thanks.
The loop continuation condition for your loop is bool == true, which is false when the loop starts and so the loop will never execute. Use this instead:
for(var i = 999; i > 0 && !bool; i = (i - 1)) {
or this to strictly obey the "three-digit number" requirement:
for(var i = 999; i >= 100 && !bool; i = (i - 1)) {
I'd also suggest finding a better variable name than bool. found would be appropriate here.
Your breaking condition is wrong here change it to:
Here is Demo
var bool = false;
for(var i = 999; !bool; i--) {
if(i % 2 == 1 && i % 3 == 2 && i % 4 == 3 && i % 5 == 4) {
bool = true;
alert(i);
}
}

Javascript Fizzbuzz Issue

I'm trying to do some simple tests to help further my javascript knowledge (which is quite fresh). Goal 1 is to print numbers from 1-100 that aren't divisible by 5 or 3.
I tried the following:
for (var i = 1; i <= 100; i ++)
{
if (i%3 !== 0 || i%5 !== 0){
console.log(i);
}
}
This logs EVERY number from 1-100, and I can't tell why. Probably the simplest simplest questions here but it's doing my head in!
I think you mean &&, not ||. With ||, you're basically testing to see if the number is not divisible by 3 or by 5 - only if a number is divisible by both do you reject it (in other words, multiples of 15).
The typical answer to FizzBuzz is:
if( i%3 == 0 && i%5 == 0) FizzBuzz
elseif( i % 3 == 0) Fizz
elseif( i % 5 == 0) Buzz
else number
So to get directly to the number you need for i%3==0 to be false AND i%5==0 to be false. Therefore, you want if( i%3 !== 0 && i%5 !== 0)
Here's a quite simple FizzBuzz function that accepts a range of numbers.
function fizzBuzz(from, to) {
for(let i = from; i <= to; i++) {
let msg = ''
if(i % 3 == 0) msg += 'Fizz'
if(i % 5 == 0) msg += 'Buzz'
if(msg.length == 0) msg = i
console.log(msg)
}
}
fizzBuzz(1, 25)
As for a more complex solution, that's one way you could define a higher order function which generates customized FizzBuzz functions (with additional divisors and keywords)
function fizzBuzzFactory(keywords) {
return (from, to) => {
for(let i = from; i <= to; i++) {
let msg = ''
Reflect.ownKeys(keywords).forEach((keyword) => {
let divisor = keywords[keyword]
if(i % divisor == 0) msg += keyword
})
if(msg.length == 0) msg = i
console.log(msg)
}
}
}
// generates a new function
const classicFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5 })
// accepts a range of numbers
classicFizzBuzz(1, 25)
const extendedFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 })
extendedFizzBuzz(1, 25)
I attacked this the same was as Niet the Dark Absol:
for (var n = 1; n <= 100; n++) {
if (n % 3 == 0 && n % 5 == 0)
console.log("FizzBuzz");
else if (n % 3 == 0)
console.log("Fizz");
else if (n % 5 == 0)
console.log("Buzz");
else
console.log(n);
}
However, you can also do it this way:
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
One of the hardest parts of learning JavaScript - or any language - for me is understanding solutions can come in many ways. I like the first example more, but it's always good to keep thinking and look at other options.

JavaScript if statement test for one or the other but not both

Hello fellow StackOverflowers. I'm have a brain fart right now, and I cannot seem to figure this out.
I have the following code
if ((n % 3 === 0 || n % 5 === 0) &&( n % 3 !== 0 && n % 5 !== 0))
{
return true;
}
else {
return false;
}
Basically I need to test if the number is a multiple of 3 || 5 but not a multiple of both.
However when I enter any number I enter (whether it is multiple of 3 || 5 || both) the test always fails. I would have thought this was able to be performed in one statement.
This code though does work fine.
if (n % 3 === 0 || n % 5 === 0)
{
if( n % 3 === 0 && n % 5 === 0)
{
return false;
}
else {
return true;
}
}
else {
return false;
}
But I'm wondering what I am missing in the first test. I'd like all the test to be in one like, but like I said I'm having a brain fart and cannot figure out what I'm missing.
You can use the XOR operator, alternatively
return (n % 3 === 0 ^ n % 5 === 0);
If it is divisible by both 3 and 5, it'll be divisible by 15.
Please try the following condition
if ((n % 3 === 0 || n % 5 === 0) && ( n % 15 !== 0))
change
if ((n % 3 === 0 || n % 5 === 0) &&( n % 3 !== 0 && n % 5 !== 0))
to
if ((n % 3 === 0 || n % 5 === 0) && !(n % 3 === 0 && n % 5 === 0))
The first part of your logic is to determine if the number in question is a multiple of 3 or 5 whereas the second SHOULD be about wether only one of them is. So... I changed the second part to see if both match it and then I NOT'ed that.
It should be: if ((n % 3 === 0 || n % 5 === 0) &&( n % 3 !== 0 || n % 5 !== 0))
return (n % 3 === 0 && !(n % 5 === 0)) || (n % 5 === 0 && !(n % 3 === 0));
(untested)
Your second check is wrong:
if ((n % 3 === 0 || n % 5 === 0) &&**( n % 3 !== 0 && n % 5 !== 0)**)
Change it to:
(! (n%3 === 0 && n % 5 === 0 ) )
This is a short version of XOR implementation using conditional statement in javascript
if((n % 3 === 0)? (n % 5 !== 0) : (n % 5 === 0)) {
...
}
or you can also compare in this way, checking when the two conditions, when evaluated as boolean, return different values (one is true and other is false or vice-versa)
if( (n % 3 === 0) !== (n % 5 === 0)) {
...
}
so this code can be written really short

Math calculation issue with Javascript

I am having a bit of trouble with a few math calculation in javascript.
The goal of this calculation is to generate a value when the user clicks on a text field.
For example:
1 Kilogram costs 32 cents to ship to America and the user wants to find out what 10KG will cost him which is $3.20. For this I have the following piece of javascript code:
function calculate(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) multiplyBy = 0.32;
if(num == 2) multiplyBy = 0.14;
if(num == 3) multiplyBy = 0.24;
if(num == 4) multiplyBy = 0.53;
var sum = parseInt(document.getElementById('weight'+num).value) * multiplyBy;
if(isNaN(sum)) return false;
price.value = sum;
}
The above code works perfectly fine, however when I reverse the process (someone has $3.20 and wants to find out how much KG he/she can ship with that (which is 10KG) the script returns: 9.375KG
The following code is used for this calculation:
function reverse(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) divideBy = 0.32;
if(num == 2) divideBy = 0.14;
if(num == 3) divideBy = 0.24;
if(num == 4) divideBy = 0.53;
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
if(isNaN(sum)) return false;
weight.value = sum;
}
I honestly don't grasp why it is failing, It would be much appreciated if someone could help me out with this.
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
You are forcing price into an integer before dividing it. So if price is 3.20, you are actually dividing 3 / 0.32, which is 9.375.
Don't force it into an integer.

Categories

Resources