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.
Related
I'm learning Javascript and trying to make a function that compares a current letter of a string with the one succeeding it, repeating through the entire string to then determine if it is alphabetical. My if condition is what's wrong, but I'm not sure how I'd change it to make it work.
Also, I'd like to keep the structure similar to what I have if possible.
function is_alphabetical(string) {
let result;
for ( i = 0; i < string.length; i++ ) {
if ( string[i] <= string[i + 1] ) {
result = true;
} else {
result = false;
break;
}
}
return result;
}
Have a look into localCompare function e.g.
"a".localeCompare("b")
>> -1
"a".localeCompare("a")
>> 0
"b".localeCompare("a")
>> 1
in your case:
if((string[i + 1]).localCompare(string[i]))
Hope that helps :)
By keeping the structure similar as you asked, I think this solution works:
function is_alphabetical(string) {
for ( i = 0; i < string.length; i++ ) {
if ( string[i] >= string[i + 1] ) {
return false;
}
}
return true;
}
Here's how I would do it.
function isAlphabetical(str) {
// we iterate only while i<length-1 to avoid going out of bounds when doing str[i+1]
for (let i = 0, n = str.length - 1; i < n; i++) {
if (str[i] > str[i + 1])
return false; // at least one letter is making it not ordered
// else keep checking other letters
}
return true; // if we reached here, its ordered
}
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));
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);