The following code only produces an output true. How to debug it? - javascript

I have the following code to generate prime numbers. However, instead of generating prime number, it generates the entire list on numbers from 2 to the number that is fed into the function. How to resolve this?
var i = 2;
var primeCheck = function(number){
while(i<number){
if(number%i===0)
{
break;
}
i++;
}
if (i===number)
{
return true;
}
};
var primeGen = function(limit){
for(k=2; k<=limit; k++)
{
if(primeCheck(k)){
console.log(k);
}
}
};
primeGen(10);
EDIT: I realized that I was quite unclear with my question. So I updated it. My guess is that the "return true" is causing this nuisance. Therefore I had asked my previous question based on that.

If you want to return something you have to return instead of alert; break. I would consider refactoring this though. First of all, you should never have a function that performs such a simple task rely on an outside variable. Keep it modular.
function isPrime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1
}
This will return true if the number is prime and false otherwise. This is useful because you now have the flexibility to do multiple things with it. If you want to return true or false, it does that. If you want to output something else like "prime" or "not prime" it's very easy to wrap further.
function isPrimeText(num) {
return isPrime(num) ? "Prime" : "Not Prime"
}

Your if condition that returns the alert runs with primecheck() without parameters. Correct it to:
if (primeCheck(11)) {
alert("prime");
}
Also, remove the last line with the call to primeCheck(11).

Just use primeCheck(11) in your condition where you want to put alert
There is some error in your logic, when I try with primeCheck(12) it does not gives intended result.
var i = 2;
var primeCheck = function(number){
while(i<Math.floor(Math.sqrt(number))){
if(number%i===0)
{
alert("Not a prime");
break;
}
i++;
}
if (i===Math.floor(Math.sqrt(number)))
{
return true;
}
};
//now check for prime or not prime
if(primeCheck(11))
{
alert("prime");
}
if(!primeCheck(12))
{
alert("not prime");
}

Related

Count each character in string using recursion

i have tried to make a function count each character in a string using recursion, for 2 days now. I tried to write some pseudo-code, but i can't really implement it.
Pseudocode:
write a function that takes text as a parameter
set a counter, for each element
set a result, using key,value for each character in element
base case: if we only have 1 string, then return the character and string
else return function-1 until the last element is hit.
var tekst = "We have to count strings";
function countStrings(tekst) {
var count = 0
var result = {}
if (count > tekst.lentgh) {
count++
return result
} else {
return countStrings(tekst-1)
}
}
console.log(countStrings(tekst))
Consider using this logic:
var tekst = "We have to count strings";
function countStrings(tekst) {
if (tekst.length == 0) {
return 0;
}
return 1 + countStrings(tekst.substring(1));
}
console.log(countStrings(tekst))
The approach here is, at each step of the recursion, to return 1 plus whatever the length of the substring from the next character onwards is. That is, we recurse down the input string, one character at a time, building out the length. The base case here occurs when the input to countStrings() happens to be empty string. In this case, we just return 0, and stop the recursive calls.
I decided to attempt this problem and this is what I came up with. Definitely a challenging problem so don't feel bad if you didn't get it:
var countStrings = function(tekst) {
if (tekst.length === 0) return {};
var obj = countStrings(tekst.slice(1));
if (obj[tekst[0]]) {
obj[tekst[0]] += 1;
} else {
obj[tekst[0]] = 1;
}
return obj;
};

Where do I place my return true statement

This is a basic javascript question I just want to better understand. I'm trying to understand if it matters where I place my return true statement. Here's the example code:
function isValid(input) {
for (var i = 0; i < input.length - 2; i++) {
var charOne = input.charAt(i);
var charTwo = input.charAt(i + 1);
var charThree = input.charAt(i + 2);
if (charOne === charTwo && charOne === charThree) {
return false;
}
return true;
}
}
isValid("ABB");
This returns true, but also returns true if I place the return true statement here:
function isValid(input) {
for (var i = 0; i < input.length - 2; i++) {
var charOne = input.charAt(i);
var charTwo = input.charAt(i + 1);
var charThree = input.charAt(i + 2);
if (charOne === charTwo && charOne === charThree) {
return false;
}
}
return true; // Moved this return statement
}
isValid("ABB");
Is one way wrong and the other correct?
Your first version, you are returning true within the for loop. That means its only going to execute your loop once and then return. That's likely a bug.
Your second version is likely correct. The return true statement executes from the function after the for-loop completes all iterations from [i..length-2).
second one, since in the first one after each iteration , you check if characters are equal and it will return false or return true in the first iteration itself.In, second one you check for all combinations and if it's never false then it must be true.
When you return inside a for loop you finish the whole loop and carry on outside it.
So the answer is it depends, if you want to miss out an item and carry on looping after the return statement then doing a return isn't what you want.
The return you put outside of the loop allows the loop to complete before returning the result.
Note a useful keyword you can use inside a loop if you want to finish the iteration rather than breaking the whole loop is continue.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue
I don't think one is wrong necessarily. I actually prefer a slightly different approach.
For clarity I generally will do something like this. So it is clearly one or the other.
With a return it is obvious that calculations within the function stop at that point. I just like it to look obvious.
if(charOne === charTwo && charOne === charThree) {
return false;
} {
return true;
}

Javascript - extract letters from an alphanumerical string via loop

Hello there StackOverflow people,
What I expected:
Removing the numbers of the string "23Ka5X". The loop counts the length and the if statement extracts the letters into an array letterMemory. When no letters are in the string, the message '"oh no numbers!" should be the output.
What I ran into:
I have been working on this for some time now but I can't find my mistake. I don't know if I missed a simple detail or made a big mess.
My feeling and console output:
var letterMemory = [];
function orderMsg(mixedMsg) {
for (var loopString = 0; loopString < mixedMsg.length; loopString++); {
if (isNaN(parseInt(mixedMsg.charAt[loopString]))); {
letterMemory.push(mixedMsg.charAt[loopString]);
return letterMemory;
} if (!isNaN(parseInt(mixedMsg.charAt[loopString]))) {
return "oh no numbers!";
}
}
}
console.log(orderMsg("23Ka5X"));
I feel like the issue is trying to push any letter into the array letterMemory via letterMemory.push(mixedMsg.charAt[loopString])
does not work how I imagine it.
I would be really grateful for your help!
I found a simple solution via .replace() but I really want to make it work with a loop and if statements since loops combined with if statements were my latest freecodecamp lessons and I want to get better at it.
The fixed code
function orderMsg(mixedMsg){
var letterMemory = []
for (var loopString = 0; loopString < mixedMsg.length; loopString++){
if (isNaN(mixedMsg[loopString])){
letterMemory.push(mixedMsg[loopString])
}
}
if (letterMemory.length){
return letterMemory
} else {
return 'oh no numbers!'
}
}
The issue was
The for loop was not executing since you terminated it with ; at the end.
charAt is a function, so you either do string.charAt(index), or you can also simply say string[index].
You are using the return statement within the for loop, so what will happen is even if the for loop ran (without the semi-colon at the end), it would run just once.
One other issue is that the variable letterMemory is declared outside the function so that means if you were to call this function twice, it would use the same letterMemory array.
-end of answer-
Additional read: you can use split, filter and ternary operator to condense the function as follows ..
function orderMsg(mixedMsg){
const letterMemory = mixedMsg.split('').filter(isNaN)
return letterMemory.length ? letterMemory : 'oh no numbers!'
}
This could be helpful,
function orderMsg(mixedMsg) {
for (var loopString = 0; loopString < mixedMsg.length; loopString++) {
if (isNaN(parseInt(mixedMsg.charAt(loopString)))) {
letterMemory.push(mixedMsg.charAt(loopString));
}
}
return letterMemory;
}
var arr = orderMsg("23s5");
if (arr.length == 0) {
console.log("oh no numbers!")
} else {
console.log(arr);
}
Use replace with regex globally, replacing all digits by an empty string:
string.replace(/[0-9]/g, "")
You have terminated for loop in the same line with ;.
charAt() is a method.
Return value after for loop ends.
var letterMemory = [];
function orderMsg(mixedMsg) {
for (var loopString = 0; loopString < mixedMsg.length; loopString++) {
var letter=parseInt(mixedMsg.charAt(loopString));
if(isNaN(letter)){
letterMemory.push(mixedMsg.charAt(loopString));
}
}
if(letterMemory.length>0){
return letterMemory;
}
else{
return "Oh no numbers!";
}
}
console.log(orderMsg("23Ka5X"));
Maybe try using .test to match the letters.
function orderMsg(str){
var result = [];
for(var letter of str){
if(/[a-zA-Z]+/g.test(letter)){
result.push(letter)
}
}
if(result.length === 0){
return 'Oh no numbers'
}
return result
}
For a more thorough explanation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

How i put together two functions, both with a recursion inside

I am a beginner and this my first post here(plus I'm not a native English speaker), so please forgive me if my code and/or my English are bad.Given two numbers I want to write a JavaScript function to find if the second one is a power of the first one, and then determine that power (ex: 2,8 the output must be 3). I wrote two functions, both working, but I can't put them together.
This is the first one to check if the second number is a power of the first one.
function checkNumbers(x,y){
if (y%x !==0){
return "this numbers are not valid"
}
else if(x===y) {
return "correct!"
}
else {
y=y/x
return checkNumbers(x,y)
}
}
checkNumbers(2,8) // will give the first answer
checkNumbers(2,18) // will give the second answer
The second function will give you the integral logarithm:
count =1;
function findGrade(x,y) {
if(y/x===1)
return "the grade is " + count;
count++;
y = y/x;
return findGrade(x,y)
}
findGrade(2,8) // output 3
findGrade(2,16) // output 4
How can I put them together into one function? I think i need a closure, but I didn't find the way to make that work.
checkNumbers should return a Boolean value, not a message. Then findGrade can check that result to see whether it should compute the logarithm. Something like this:
function checkNumbers(x,y){
if (y%x !==0){
return false
}
else if(x===y) {
return true
}
// the rest of your function remains the same.
function findGrade(x,y) {
// First, check to see whether y is a power of x
if checkNumbers(x,y) {
// your original findGrade function goes here
}
else
return -1; // Use this as a failure code.
Does this work for you?
Another possibility is to combine the functions entirely: try to find the logarithm (what you call "grade"); if it works, you get your answer; if it fails (at y%x !== 0), then you report the failure.
The solution is, in fact, pretty simple.
You could do the following:
function findGrade(x, y, count = 1) {
// If the numbers are not valid, throw an error. The execution is interrupted.
if(y % x != 0) throw "Invalid inputs";
// If the inputs are different, continue the execution and add 1 to count.
if(x != y) return findGrade(x, y/x, ++count);
// If none of the above are true, you have your result!
return count;
}
Tests:
console.log(findGrade(2, 8)); // Outputs 3
console.log(findGrade(2, 16)); // Outputs 4
console.log(findGrade(2, 3)); // Error: Invalid inputs
console.log(findGrade(3, 3486784401)); // Outputs 20
Please let me know if you need any further help.
I'm not sure if my method is different, but I have implemented it below. In real world application I would do some more typechecking on inputs and check if there is a third argument: if not default to 0 (First Iteration default the count to 0), but this is the general idea. You can run the snippet below.
// Arguments
// 1: Base of Exponent
// 2: test Number
// 3: count by reference
function checkPower (base, test, count) {
let division = test/base
// base case
if (division === 1) {
count++
return count
} else if (division < 1) {
console.log("not a power")
return;
}
// iteration step
count++
return checkPower(base, division, count++)
}
// Test Cases
let test = checkPower(2, 32, 0)
if (test) {
console.log(test) // 5
}
test = checkPower(2, 1024, 0)
if (test) {
console.log(test) // 10
}
test = checkPower(2, 9, 0)
if (test) {
console.log(test) // "not a power"
}

Javascript : How can I add X elements to an array

I need to create an array including the first 100 prime numbers, here is my code:
var premier= [];
var nombre= premier.length;
function isPrime(n)
{
if(n < 2)
{
return false;
}
for(i=2; i<Math.sqrt(n); i++)
{
if(n%i===0)
{
return false;
}
}
return true
};
while(nombre<100)
{
var j=2
if(isPrime(j)==true)
{
premier.push(j);
}
j=j+1
}
I am a beginner in Javascript, but I have tested the isPrime function and it works fine even forlarge numbers.
but when I run the program I have:
FATAL ERROR: JS Allocation failed - process out of memory
I think this part is wrong:
while(nombre<100)
{
var j=2
if(isPrime(j)=true)
{
premier.push(j);
}
j=j+1
}
console.log(premier)
But I can't tell why
You are repeatedly setting j=2 every time the loop runs, and you never change nombre so the loop will never end. Note that JavaScript sets literal vaues by value, not by reference, so nombre = premier.length won't magically update.
Additionally, statements of the form if( x = true) will set x to true, and then pass the condition automatically. In this case, since x is a function call, it is invalid syntax.
Did you mean this?
var j = 2;
while(premier.length < 100) {
if( isPrime(j)) premier.push(j);
j++;
}

Categories