Calculate closest gift position using javascript - javascript

I tried one practice and check the requirement below.
You are on your way to find the gifts. All the gifts lie in your path in a straight line at prime
numbers and your house is at 0.
Given your current position find the closest gift to your position, and calculate the distance
between your current position and gift and tell the distance.
Ex:
For input 0, the output is 2
For number = 11, the output should be 0
For number = 2000000000, the output should be 11 For number = 1800000001, the output
should be 10
For the above logic I tried to use javascript and almost I have completed but i'm not getting the proper outpu as per the requirement,my output is returning any number.
Javascript
function isPrime(num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true
} else if (num % 2 === 0 || num % 3 === 0) {
return false
}
let i = 5
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) {
return false
}
i += 6
}
return true
}
HTML
<h1> Gift House</h1>
<label for="name">Enter a house Number</label>
<input type="text" id="inp" class="clr" />
<input type="button" id="checker" value="Calculate" onClick="findpos()">
<label for="name"> Distance of the gift house</label>
<input type="text" id="demo" value="" class="clr">

I understood your requirement,you have tried 2 steps properly but before those two steps you have to do one more logic to calculate prime number.Because you have called the function isPrime in your JS but where you defined the function?
Just include the below script in your JS code and check the output.
function findpos() {
var num = document.getElementById("inp").value;
var pos = 0;
while (true) {
if (isPrime(num)) {
break;
} else {
pos++;
num++;
}
}
document.getElementById("demo").value = pos;
}

Where is the isPrime function? how you called without defining the function.I think this is what the reason for your issue.
Check my below example,
function findpos() {
var num = document.getElementById("inp").value;
var pos = 0;
while (true) {
if (isPrime(num)) {
break;
} else {
pos++;
num++;
}
}
document.getElementById("demo").value = pos;
}
function isPrime(num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true
} else if (num % 2 === 0 || num % 3 === 0) {
return false
}
let i = 5
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) {
return false
}
i += 6
}
return true
}

Related

Optimizing and finding edge cases that I might have missed - 2 coding interview questions

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;
}

Find and print the biggest prime number (JS)

I'm studying node.js and have some interesting task - Write a program that finds and prints the biggest prime number which is <= N.
Input // Output - 13 // 13
126 // 113
26 // 23
In last course with java i have the same task and my code is really simple:
import java.util.Scanner;
public class BiggestPrimeNumber {
public static void main(String[] args){
int n;
Scanner in = new Scanner(System.in);
n=in.nextInt();
while(prim(n) == false){
n--;
}
System.out.println(n);
}
public static boolean prim(int m){
int n=m;
for(int i=2;i<n;i++){
if(n%i == 0){
return false;
}
}
return true;
}
}
I try similar way to test it, but I'm don't have idea how to convert it:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
Can you help me, because I'm really have problem with js using in console.
I think this is what you want. You only need to declare a function and use it as you are doing.
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
If your running it with NodeJS in console, you can save it in a file called prime.js (for example) and execute it with: node prime.js.
You can pass parameters to the script like: node prime.js 126 and then get them in the code. That will be something like that:
const args = process.argv;
let n = args[2];
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
You're pretty close. First off, you don't have isPrime defined. Second, if you were to paste all of your code into the browser console, it isn't going to like that you are defining n twice. I also cleaned up your isPrime bit of code.
let n = 100;
let result = n;
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}
while (isPrime(result) === false) {
result -= 1;
}
console.log(result + " is the next prime below " + n);
Also, remember that javascript is not a compiled language, so unless you are defining your function in a class, the browser will interpret the code sequentially. Therefore, you have to have isPrime defined before you use it.
The algorithm to find the nearest prime number can be further optimized. All prime numbers are of the form 6k+1 or 6k-1 except the numbers 2 and 3. Also, instead of checking all the way to the number the check can be made till Sqrt(n). Here is the modified isPrime function:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(num) {
if (num <= 1) return false;
if (num < 4) return true;
if (num%2 === 0 || num%3 === 0) return false;
for (var i = 5; i*i <= num; i+=6) {
if (num % i === 0 || num % (i + 2) === 0)
return false;
}
return true;
}

checkPrime function returns incorrect values

numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num in numbers) {
if (num % i === 0) return num + ' is not prime';
else {
return num + ' is prime';
}
return num !== 1;
} else {
return num + ' is not in range';
}
}
}
console.log(checkPrime(27));
Hi.
In the above code, I tried to create a function which returns information about whether a number is prime or not.
However, it fails in some cases. Like eg. in the case of 27 or 145, it returns the values are prime, which obviously is false. How can I amend this program to make it work?
Also, what is the smartest way of merging the case for number 2 and the rest prime numbers?
Thanks in advance and sorry if this is too basic, I could not find the right answer anywhere else.
You are putting the 'else' clause that states the number is prime before having finished to check all numbers until itself -1.
To be optimal, you don't need to loop until the number ( < num). Just until the square root of the number. (even better than looping until num/2) For example : 167 can be seen that is prime when the loop has reached 13. 13*13 = 169 > 167 so you can stop and safely afirm that 167 is prime.
For number 2 it is correct to have a sepparate case.
Below is the code for checking a single value if it is prime:
function checkPrime(num) {
if (num == 1 || num === 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < Math.sqrt(num); i++) {
if (num % i === 0) return num + ' is not prime';
}
return num + ' is prime';
}
alert(checkPrime(27));
I have rewritten the code to provide the right answer
numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
// check this condition outside the loop
if (!(num in numbers)) {
return num + ' is not in range';
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return num + ' is not prime';
}
}
return num + ' is prime';
}
console.log(checkPrime(27));
I've rewritten your code and made a couple of changes.
The reason you were having your problem is that you were returning in the for loop meaning all odd numbers would declare themselves as prime numbers.
I've fixed this but also I've I rearranged things a little, to be as efficient as possible it's good to bail as soon as possible so I do a couple of checks to bail initially I check if the number is in range, if not bail.
I've commented the code so it makes sense but if you don't understand why I've done something feel free to ask.
// make an array of all numbers between 0 and 10000
numbers = [];
for (x = 0; x <= 1e4; x++) {
numbers.push(x)
}
function checkPrime(num) {
// return if input number is not in numbers array
if (numbers.indexOf(num) == -1) return num + ' is not in range'
// return if number is 0 or 1
if (num <= 1) return 'It is a separate case'
// check all numbers between 2 and input number
// return if any number devides neatly
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
// if you get this far it's prime
return num + ' is prime';
}
console.log(checkPrime(27));
Personally, for the range, I wouldn't have an array of all the values but I've left this in just in case there was some other reasoning we don't know about.
EDIT:
As you've said the initial array is not important I've remade the code to work without it, I've not included comments this time (to save space) but that code does the same thing and is mostly unchanged.
function checkPrime(num) {
if (num < 0 || num > 1e4) return num + ' is not in range'
if (num <= 1) return 'It is a separate case'
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
return num + ' is prime';
}
console.log(checkPrime(27));
Anyway, I hope you find this helpful 🙂

Check for perfect number and print out divisors?

My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}

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.

Categories

Resources