I am trying to achieve a check with the if...else statement that only squares the odd numbers between 100 and 150, otherwise the number is just printed.
How can I revise my if statement to achieve this please? An educated guess is that an operator or combination of operators are used.
for (i=100; i<=150; i++)
{
if (i === 0)
{
console.log(i * i);
}
else
{
console.log(i);
}
}
The operator you are looking for is %:
for(i = 100; i <= 150; i++) {
if(i % 2 === 1) { // It's odd
console.log(i * i);
} else {
console.log(i);
}
}
a % b is basically the remainder obtained when a is divided by b. It's called the modulus operator.
Two words: Modulus Division
A nice reference
if ( i % 2 === 0) {
console.log(i)
} else {
console.log(i * i)
}
Squares odd numbers.
Related
I am trying to understand recursion.
I am stuck with the following: I need to add up the numbers from a single number so if I call addUp(4) it should return 10 (4+3+2+1).
I came up with the below solution but it does not count the last number (1).
I know that the solution is to change the condition to "num===0" but I don't see the difference: in my head, my solution should work as well.
function addUp(num) {
if (num < 0) {
return num;
}
return num + addUp(num - 1);
}
console.log(addUp(4)); // 9
You need to check for less than or equal to zero. You want to stop if you hit zero as well. A log statement helps identify this.
Alternatively, you could evaluate num < 1.
function addUp(num) {
console.log(`Attempting to add: ${num}`);
if (num <= 0) {
return num;
}
console.log(`Added: ${num}`);
return num + addUp(num - 1);
}
console.log(`Total: ${addUp(4)}`);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Code golf
The following code is only 19 bytes:
f=n=>n<1?n:n+f(n-1)
You can simplify this code and write it in one expression without recursion:
function addUp(num) {
return num*(num+1)/2;
}
The stopping condition should be num <= 0 and not num < 0.
function addUp(num) {
if (num <= 0) {
return num;
}
return num + addUp(num - 1);
}
console.log(addUp(3));
FLOWCHART
I want to know how I can improve my code by helping it find out what number is prime and what is not. I was thinking that I would divide a number by a number and then if it is a decimal number then it is prime,
I want it to have a loop to check every number 1 to 100 and see if it is a prime number
This is what I have so far:
for(let i = 1; i <= 100; i++) {
if(i == 1) {
}else if(i == 2) {
console.log(`${i} is a prime number`);
}else if(i >= 3){
x = i / 2;
tf = Number.isInteger(x);
if(tf == false && i >= 3) {
console.log(`${i} is a prime number`);
}
}
}
and so far it outputs 1 2 and all the odd numbers.
Create a function to test whether a number is prime or not (divisible only by 1 and itself). Then call this function inside the loop on each number.
function isPrimeNumber(no) {
if (no < 2) {
return false;
}
for (let i = 2; i < no; i++) {
if (no % i == 0) {
return false;
}
}
return true;
}
for (let i = 1; i <= 100; i++) {
if (isPrimeNumber(i)) {
console.log(i);
}
}
var numbers = new Array(101).fill(0).map((it, index) => index);
var halfWay = Math.floor(numbers.length / 2);
for (let i = 2; i <= halfWay; i++) {
if (!numbers[i]) continue;
for (let j = 2; j * i < numbers.length; j++) {
console.log(`${i} * ${j} = ${i * j}`);
numbers[j * i] = null;
}
}
console.log(numbers.filter(it => it));
Here is an attempt to mathematically find numbers between 1-100 that are primes.
Fill an array of numbers 0-100
For every number (starting at 2), multiply it by itself and all numbers after it, up to half of the array
For every computed number, remore it from the array, as it is not a prime
At the end, filter out all numbers that are null
As Taplar stated primes are numbers that only divide by the number itself and 1.
As far as improving your code. I would say you want to eliminate as many possible numbers with the fewest questions.
An example would be is the number even and not 2 if so it is not prime? The interesting part of this question you eliminate dividing by all even numbers as well. This instantly answers half of all possible numbers and halves the seek time with the ones you need to lookup.
So what would this look like?
function isPrime(num) {
// Check it the number is 1 or 2
if (num === 1 || num === 2) {
return true
}
// Check if the number is even
else if (num % 2 === 0) {
return false;
}
// Look it up
else {
// Skip 1 and 2 and start with 3 and skip all even numbers as they have already been checked
for (let i = 3; i <= num/2; i+=2) {
// If it divides correctly then it is not Prime
if (num % i === 0) {
return false
}
}
// Found no numbers that divide evenly it is Prime
return true
}
}
console.log('1:', isPrime(1))
console.log('2:', isPrime(2))
console.log('3:', isPrime(3))
console.log('4:', isPrime(4))
console.log('11:', isPrime(11))
console.log('12:', isPrime(12))
console.log('97:', isPrime(97))
console.log('99:', isPrime(99))
console.log('65727:', isPrime(65727))
console.log('65729:', isPrime(65729))
Background - I took an online coding test and was presented with questions similar to this, I did rather poorly on it compared to the hidden grading criteria and I was hoping to get another pair of eyes to look at it and maybe help point out some of my mistakes.
Practice Test questions -
Task: Given an integer inject the number 5 into it to make the largest possible integer
Conditions: (-80000...80000) range needed to handle
Expected input: int
Expected output: int
Testcase: -999 -> -5999
80 -> 850
var lrgInt = function(num) {
var stringInt = num.toString();
for (let i = 0; i < stringInt.length; i++) {
if (stringInt.charAt(i) === "-") {
return parseInt([stringInt.slice(0, 1), '5', stringInt.slice(1)].join(''));
}else if (stringInt.charAt(i) < 5) {
return parseInt([stringInt.slice(0, i), '5', stringInt.slice(i)].join(''));
}
}
return parseInt([stringInt.slice(0, stringInt.length), '5', stringInt.slice(stringInt.length)].join(''));
};
Task: Determine the number of operations done on a number following the conditions to reduce it to 0.
Conditions:
- If the number is odd, subtract 1
- If the number is even, divide by 2
Expected input: int
Expected output: int
var operations = 0;
var numberOfSteps = function(num) {
if (num === 0){
return operations;
}else if (num % 2 == 0) {
operations++;
return numberOfSteps(num/2);
} else {
operations++;
return numberOfSteps(num-1);
}
};
For the second question, you could add one plus the result of recursion with the adjusted number without having a global counter.
function numberOfSteps(number) {
if (!number) return 0;
if (number % 2) return 1 + numberOfSteps(number - 1);
return 1 + numberOfSteps(number / 2);
}
console.log(numberOfSteps(5)); // 5 4 2 1 0
For the first question, we make the observation that if the number is positive, we want to inject the 5 before the first digit less than 5, but if it's negative then we want to inject it before the first digit greater than 5. For the second problem, we can just use a simple while loop.
function largestNum(num) {
if (num == 0) {
// this edge case is weird but I'm assuming this is what they want
return 50;
}
var negative = num < 0;
var numAsStr = Math.abs(num).toString();
var inj = -1;
for (var i = 0; i < numAsStr.length; i++) {
var cur = parseInt(numAsStr[i], 10);
if ((!negative && cur < 5) || (negative && cur > 5)) {
// we found a place to inject, break
inj = i;
break;
}
}
if (inj == -1) {
// didn't inject anywhere so inject at the end
inj = numAsStr.length;
}
return (
(negative ? -1 : 1) *
parseInt(numAsStr.substr(0, inj) + "5" + numAsStr.substr(inj))
);
}
function numSteps(num) {
var steps = 0;
while (num != 0) {
if (num % 2) {
// it's odd
num--;
} else {
num /= 2;
}
steps++;
}
return steps;
}
I am trying to do something with JS but as per usual arrays prove to be the bane of my existence...
I have to loop through the numbers from 1 to 100 and print them in the HTML, every number that divides by 3 should show in the colour red while all other numbers should be black. I tried so many things and tried to find how to do it but could not figure it out. Could anyone, please, tell me what is the proper way to do it?
You can use the following code to get what you are looking for.
for (let i = 1; i < 101; i++) {
if(i % 3 == 0) {
console.log('THREE');
} else {
console.log(i)
}
}
If you need to write the values to a document, change the console.log to document.write
Put the THREE in some inline element and add css rule to change the color.
For printing the list the solution explained by Jack. (Did it differently because I could.)
const text = (new Array(100))
.fill('')
.map((_v, i) => (i % 3) === 0 ? `<b>THREE</b>` : i)
.join('<br/>');
document.write(`<p>${text}</p>`)
b {
color: red;
}
First, loop through the numbers 1 to 100:
for (var i = 1; i <= 100; i++) {
//Stuff will go here
}
Then, write the number i to HTML:
document.write(i);
Finally, add the if statement:
if (i % 3) {
document.write(i);
} else {
document.write("THREE");
}
Full code:
for (var i = 1; i <= 100; i++) {
if (i % 3) {
document.write(i + "<br>");
} else {
document.write("THREE<br>");
}
}
EDIT
Here's how you'd make THREE red:
for (var i = 1; i <= 100; i++) {
if (i % 3) {
document.write(i + "<br>");
} else {
document.write("<span style='color: red;'>THREE</span><br>");
}
}
Is there an efficient way to check if number belongs to Fibonacci sequence?
I've seen many examples with a loop that creates the sequence in an array and checks every time if newly generated number of the sequence is equal to the input number. Is there another way?
http://www.geeksforgeeks.org/check-number-fibonacci-number/
This link details that there is a special quality about fibonacci numbers that means that a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square.
So,
function (num) {
if (isSquare(5*(num*num)-4) || isSquare(5*(num*num)+4)) {
return true;
} else { return false; }
}
Then isSquare would just be a simple checking function.
Edit: Worth noting that while this is a much more efficient and easy way to find fibonacci numbers, it does have an upper bound. At about the 70th Fibonacci number and above, you may see issues because the numbers are too large.
function isFibonacci(num, a = 0, b = 1) {
if(num === 0 || num === 1) {
return true;
}
let nextNumber = a+b;
if(nextNumber === num) {
return true;
}
else if(nextNumber > num) {
return false;
}
return isFibonacci(num, b, nextNumber);
}
function isPerfectSquare(n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
//Equation modified from http://www.geeksforgeeks.org/check-number-fibonacci-number/
function isFibonacci(numberToCheck)
{
// numberToCheck is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perferct square
return isPerfectSquare(5*numberToCheck*numberToCheck + 4) ||
isPerfectSquare(5*numberToCheck*numberToCheck - 4);
}
for(var i = 0; i<= 10000; ++i) {
console.log(i + " - " + isFibonacci(i));
}
This will most likely fail for larger numbers though.
def is_squared(number):
temp_root = math.sqrt(number);
temp_root = int(temp_root);
return (temp_root * temp_root == number);
def check_all_fibo(test_number_list):
result_fibo_list = [];
for item in test_number_list:
if item==0 or item == 1 or item == 2:
result_fibo_list.append(item);
continue;
if is_squared(5 * item * item - 4) or is_squared(5 * item * item + 4):
result_fibo_list.append(item);
return result_fibo_list;
this is a python implementation by me. But keep in mind, the formula only works when the fib is not too large.
The Fibonacci sequence is a series of numbers where a number is the addition of the last two numbers, starting with 0, and 1. Th following js function is explaining this.
function isFabonacci(n) {
if (n === 1 || n === 0) {
return true;
}
let firstPrevNumber = n - 1;
let secondPrevNumber = n - 2;
return (firstPrevNumber + secondPrevNumber === n);
}
// isFabonacci(2) -> false
// isFabonacci(3) -> true