Could someone please help me find the error in this code? I'm reading through what I came up with and it logically makes sense to me each step of the way, but it's not producing the desired result. At the end I test calling the function with 6.
function is_prime(num) {
if (isNaN(num)) return false;
var numFactors = 0;
for (i=1; i<=num; i++) {
if (num % i === 0) {
numFactors += 1;
}
return numFactors;
}
if (numFactors === 2) {
return true;
}
else {
return false;
}
}
console.log(is_prime(6));
You are returning the function from inside the forloop.
So it never hits the other statements
Check Fiddle
I believe the problem you are having is that you are potentially returning your numFactors too early:
for (i=1; i<=num; i++) {
if (num % i === 0) {
numFactors += 1;
}
return numFactors;
}
Here, you are returning the numFactors at the end of your first loop, so it never actually finishes the full test.
Counting factors is not a right approach -
use this -
function is_prime(num) {
if (isNaN(num)) return false;
var k = Math.sqrt(num);
for (i=2; i<=k; i++) {
if(num%i===0)return false;
}
return false;
}
console.log(is_prime(6));
As you are stepping through all numbers from 1 to num for factrorization you might as well pick them up as factors and get a bit more out of your function:
function fact(num) {
if (isNaN(num)) return false;
var Factors=[];
for (i=1; i<=num; i++) {
if (num % i == 0) Factors.push(i)
}
return Factors
}
console.log('factors: '+fact(27));
console.log('is prime: '+fact(27).length===2);
Related
What have I done wrong with this code? It can't print anything on the console.
Here it is the description of the problem:
Implement a javascript function that accepts an array containing an integer N and uses an expression to check if given N is prime (i.e. it is divisible without remainder only to itself and 1).
var n = ['2'];
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for(var i = 2; i < Math.sqrt(n); i += 1) {
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
return isPrime(n);
There are couple errors in your code.
First, you need to check for every integer between 2 and Math.sqrt(n) inclusively. Your current code returns true for 4.
I don't think this is in a function, so you need to omit return from return isPrime(n) and replace it with a function wich prints out the return value of the funnction, like alert or console.log.
n is not a number, it's an array. You need to either make n a number, or call the function with isPrime(n[0]).
The correct code is
var n = 2;
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for(var i = 2; i <= Math.sqrt(n); i += 1) {
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
alert(isPrime(n));
Note: You can change n += 1 to n++, and it works the same way.
n is an array, you want to access first element in the array and convert it to number first.
try replacing
return isPrime(n);
with
return isPrime(parseInt(n[0],10));
Your for-loop condition also needs a little modification
for(var i = 2; i <= Math.sqrt(n); i += 1) { //observe that i is not <= Math.sqrt(n)
A couple of little errors:
var n = 2;//<--no need to put n in an array
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for(var i = 2; i < Math.sqrt(n); i += 1) {
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
isPrime(n);//<--no need for "return"
As to no output being printed, it is because you need to use console.log.
Replace return isPrime(n); with console.log(isPrime(n));.
Full working code:
var n = ['2', '3', '4', '5', '6', '7']; // you can use as many values as you want
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for (var i = 2; i <= Math.sqrt(n); i += 1) { // Thanks to gurvinder372's comment
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
n.forEach(function(value) { // this is so you can iterate your array with js
console.log('is ' + value + ' prime or not? ' + isPrime(value)); // this so you can print a message in the console
});
/*
// Another approach of parsing the data, uncomment this piece of code and comment the one above to see it in action (both will give the same result)
for (index = 0; index < n.length; ++index) {
console.log('is ' + n[index] + ' prime or not? ' + isPrime(n[index])); // this so you can print a message in the console
}
*/
I've read the dozen variations on this question, but those answers haven't led me to what must be an obvious mistake. Why does this always return false? Why do I see called again even after a found it? And if I put a return in front of the recursive call, why do I never see found it?
function subResult (object, start, target){
console.log('called again')
if (start === target){
console.log('found it')
return true
} else {
for (var i = 0; i < object[start].edges.length; i++){
subResult(object, object[start].edges[i], target)
}
}
return false
}
Change
for (var i = 0; i < object[start].edges.length; i++){
subResult(object, object[start].edges[i], target)
}
to
for (var i = 0; i < object[start].edges.length; i++){
if (subResult(object, object[start].edges[i], target)) {
return true;
}
}
I.e. when found your done. If not keep going.
I'm trying to create a script that returns the factorial of the input number as part of a challenge. When I try to run it, it returns the proper factorial, but apparently I did it wrong somehow.
It looks like this:
function FirstFactorial(num) {
if (num > 1) {
var x = num;
for (var i = 1; i < x; i++) {
num = num * i;
}
} else if (num === 1) {
return 1;
} else {
console.log("That's not a number!");
}
return num;
}
Then I tried doing it like this, but it still doesn't work!
function FirstFactorial(num) {
if (num < 0) {
num = 0;
console.log("You have to input a number!");
}
if (num === 0) {
return 1;
}
return num * FirstFactorial(num - 1);
}
The most likely reason is that they expected and intended you to use recursion (a function that calls itself).
If you think about factorials, each builds on the result of the previous one, which is the classic case for using recursion.
(Note that I'm specifically not posting code doing this with recursion, because presumably the point here is for you to work out how to do it.)
I'm having an assignment where I have to do the FizzBuzz game in Javascript.
The problem is my loop stops after the first iteration and only return the first value (4). I may be blind to my code but I can't find where the error(s) is.
If you could please push me in the right direction I'd be happy. Thanks in advance. Regards, Thomas.
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0) {
return "fizz";
}else if( i % 5 == 0) {
return "buzz";
}else if(i % 15 == 0) {
return "fizz buzz";
}else {
return i;
}
}
}
ANSWER = (fizzBuzz(4, 22));
New code:
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
document.write ("Fizz Buzz");
}else if(i % 3 == 0) {
document.write ("Fizz");
}else if(i % 5 == 0) {
document.write ("Buzz");
}else {
document.write(i);
}
}
}
ANSWER = (fizzBuzz(4, 22));
It returns: Answer = undefined
When your code encounters the return statement, the value given is returned from the whole function. This stops the for loop from iterating any further.
These are the questions you'll need to ask yourself:
What do you want to the fizzBuzz function to do? Should it print the text somewhere, or should it return a value?
If fizzBuzz should return a value, what would you expect that it returns? One line of text? Multiple lines of text all at once?
Whatever branch is taken within your for loop, there is always a return which exits the funtion with a return value. So, when you start with 4, the program enters the else branch and returns 4.
What you want is to print the value instead of returning from the function.
Also, I can see a logical error in the code. Assume i is 15, which is divisible by 3 and 5. Your program will go into the i % 3 branch and return "fizz" instead of "fizz buzz". You may want to change your if statements and/or work with string concatenation.
Hope I could help. ;)
One of the best solution in javascript to the fizzbuzz problem
const fizzbuzz = (start, stop) => {
const arr = [];
let str;
for(let i=start; i<=stop; i++) {
str = "";
if(i%3===0) {
str = "fizz";
}
if(i%5===0) {
str += "buzz";
}
arr.push(str||i);
}
return arr;
}
console.log(fizzbuzz(0, 105));
I know this may get downvoted but I've been really frustrated for 24 hours and looking at other Euler 3 threads hasn't helped me solve this. Can someone help with my code? I think I'm very close.
function is_prime(num) {
if (isNaN(num)) return false;
for (i=2; i<=Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
else {
return true;
}
}
}
// This above part CORRECTLY finds whether a number is prime or not. Problem lies with below part.
var holder = 0;
function getBiggestPrime (end) {
for (i=2; i<=Math.sqrt(end); i++) {
while (is_prime(i) && (end%i===0))
holder = i;
return holder;
}
}
getBiggestPrime(13195);
console.log(holder);
The first method is not correct. The corrected version will be:
<script>
function is_prime(num) {
if (isNaN(num)) return false;
for (var i=2; i<=Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
//Same problem with the second method - the return should be after the for-loop ends (also, change the while to if):
function getBiggestPrime (end) {
var holder = end;
for (var i=2; i<=Math.sqrt(end)+1; i++) {
if (is_prime(i) && (end%i===0))
holder = i;
}
return holder;
}
A link to the demo.
About the second part (if I understand correctly what you're looking for) you should start from:
i = Math.sqrt(end) and go down with i-- until you find the biggest prime.