Erroneous output in printing prime numbers - javascript

The code incorrectly computes many non-prime numbers as prime, and I am not sure why. Basically the output alternates "prime" and "not prime" for the input.
#!/usr/bin/env node
for (var i = 3; i <= 30; i++) {
console.log(i + ": " + isPrime(i) + " ");
}
function isPrime(num) {
var counter;
for (counter = 2; counter < num; counter++) {
if(num % counter == 0) {
return "not prime";
}
else {
return "prime";
}
}
}

You need to return true after the loop, not inside the loop. for instance, the number is 9. first iteration if(9%2 == 0)-false else return prime. but nine is not prime. only return true after you are through iterating and you'll find the expected result.
function isPrime(num) {
var counter;
for (counter = 2; counter < num; counter++) {
if(num % counter == 0) {
return " not prime";
}
}
return " prime";
}

for (var i = 3; i <= 30; i++) {
console.log(i + ": " + isPrime(i) + " ");
}
function isPrime(num) {
var counter;
for (counter = 2; counter < num; counter++) {
if(num % counter == 0) {
return "not prime";
}
}
// only return that it is prime if it is not evenly
// divisible by all numbers less than it
// (technically you only need to check up to sqrt(num) + 1)
return "prime";
}

Fiddle
You have to return prime after the loop is done with check
for (var i = 3; i <= 30; i++) {
console.log(i + ": " + isPrime(i) + " ");
}
function isPrime(num) {
var counter;
for (counter = 2; counter < num; counter++) {
if(num % counter == 0) {
return "not prime";
}
}
return "prime";
}

num % 2 is num mod 2, which just means the remainder of the number after being divided by two.
What you would really like to do is something like this:
primes = [2]
for (var i=0;i<primes.length;i++){
if (primes[i]<sqrt(num)){
if (num % primes[i] == 0){
console.log("Not prime!");}
}
else{
console.log("prime!");
primes.push(num);
}
}
When you're determining primes, you should only be trying to construct the prime factorization of the number you're checking, otherwise you're doing FAR more work than you should be doing. Since the prime factorization is by definition constructed of primes, those are the only numbers you should check for modularity.
Additionally you should only check up to the square root of the number because any number that it is divisible by will have a matching number. Examples:
104 = 57*2
39 = 13*3
Complexity goes from O(n) to O(log(sqrt(n)) which is 4 comparisons instead of 100 even at an n of just 100 and it just keeps getting better.

the first time something misses your f(num % counter == 0) condition, it will return as not prime
the easiest thing to take your return "prime"; call out of your for-loop
function isPrime(num) {
for(counter = 2; counter < num; counter++) {
if(num % counter == 0) {
return "not prime";
}
}
return "prime";
}

Related

Javascript numbers - split/slice Prime

I am completely new to Javascript and trying to solve a simple problem now for more than two weeks and still not getting it(please help).
TASK ::::
Read a 4 digit Number e.g. 5678
Write a function
Split/separate the numbers and than build (5678, 567, 56, 5), than check if the numbers(5678, 567, 56, 5) are Prime numbers.
Give in Console/Result if 5678 a prime number or not, 567 a prime number or not and so on.
Check "if all numbers are Prime" than show result "All prime" if not show result "Not all prime".
Trying to solve the problem with (if else) but not really getting it, because i know very less about Javascript (arrays, string, split, slice) yet.
please help me understand. Thanks.
var a = 123456789;
var b = a.toString().length; //<<--->> ANTWORT: 9
document.write('ANTWORT: ',a );
for (i=0; i<b; i++) {
var x = a.toString().slice(0, -i);
document.write(x, ",");
}
function isPrime{
for(var i = 2; i < a; i++);
if(num % i === 0) return false;
return num > 1;
}
//integer is a string at the moment
integer = prompt("Enter a integer: ");
//initialize array for dictionary
dictArray = [];
stuff = document.getElementById("stuff");
//loop through all values of the string
for (var i = integer.length; i > 0; i--)
{
//take a substring from 0 to the ith char and turn it into an int
num = parseInt(integer.substring(0, i));
//add a dictionary to the array the tells what the number is
//and if it was prime or not as a bool
dictArray.push({"num": num, "prime": isprime(num)});
(dictArray[integer.length - i]["prime"]) ? stuff.innerHTML += "<br>" + num + " is prime." : stuff.innerHTML += "<br>" + num + " is not prime.";
}
function isprime(num)
{
if (num <= 3) return num >= 1;
if ((num % 2 === 0) || (num % 3 === 0)) return false;
let count = 5;
while (Math.pow(count, 2) <= num) {
if (num % count === 0 || num % (count + 2) === 0) return false;
count += 6;
}
return true;
}
//print the array
(dictArray.find(x => !x.prime) == undefined) ? stuff.innerHTML += "<br>All prime!" : stuff.innerHTML += "<br>Not all prime!";
//console.log(dictArray);
<div id="stuff">
</div>

Issue with prime number test javascript

I'm a beginner and trying to complete a prime number test but I'm running into an issue. Here is what I have:
var n = Number(prompt("Input the number you want to check for prime:"));
var i;
if (n < 2) {
alert(n + " is not a prime number.");
}
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
alert(n + " is not a prime number.");
break;
}
else {
alert(n + " is a prime number.");
break;
}
}
It's running correctly except an alert won't pop up if I input 3 or 2 and any number with a 3 in it is coming back as a prime number even if it isn't. Other than that all of my tests have worked.
Ahhh, your problem is the way you've structured the loop. You're breaking out regardless of if the check's completed.
var n = Number(prompt("Input the number you want to check for prime:"));
var i;
var isPrime = true;
if (n < 2) {
isPrime = false;
} else if (n < 4 && n >= 2) {
// isPrime is already true
} else if (n % 2 === 0) {
isPrime = false; // no divisor of 2 can be prime
} else {
var sqrtN = Math.sqrt(n);
for (var i = 3; i <= sqrtN; i = i + 2) {
if (n % i === 0) {
// Only break out of the loop if a match is found
isPrime = false;
break;
}
}
}
if (isPrime) {
alert(n + " is a prime number.");
} else {
alert(n + " is not a prime number.");
}
Or, a perhaps more organized solution:
function isPrime (n) {
n = parseInt(n);
var i;
if (Number.isNaN(n)) {
return false;
} else if (n < 2) {
// 1 is not prime
return false;
} if (n < 4) {
// 2 and 3 are prime, so why not skip checking them?
return true;
} else if (n % 2 === 0) {
// No number divisible by 2 is prime.
return false;
} else {
// This won't change, so calculate it once as suggested by Weather Vane.
var sqrtN = Math.sqrt(n);
// 4, 6, 8... All divisible by 2, and would be caught by initial check.
for (i = 3; i < sqrtN; i = i + 2) {
// Not a prime if it's evenly divisible.
if (n % i === 0) {
return false;
}
}
// Otherwise prime.
return true;
}
}
Of course. If n % i is not 0, it means that i does not divide n, but it does not mean n is prime. You must check all i in order to say that.
Moreover, don't recalculate expensive Math.sqrt(n) at each iteration. And be aware of NaN.
var n = Number(prompt("Input the number you want to check for prime:"));
function isPrime(n) {
if (n < 2 || !n) return false;
for (var i = 2; i*i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}
alert(n + " is " + (isPrime(n) ? "" : "NOT ") + "a prime number.");
Of course, this algorithm is exponential (pseudo-polynomial). Don't use it for big n. Instead, see e.g. Miller–Rabin primality test or AKS primality test, which are polynomial.
var UI = window.prompt("Enter a whole number to test as a prime number: \n", "0");
var TV = parseInt(UI, 10);
var HITS = 0;
var DD = TV;
while (DD > 0) {
if (TV % DD === 0) {
HITS++;
}
DD--;
}
if (HITS > 2) {
document.write(UI + " is a NOT prime number");
} else {
document.write(UI + " is a prime number");
}
Please have reference to old questions asked in stackoverflow
link to the old question

Euler #2 Fibonacci Javascript function will only return zero after crunching the numbers

I wrote a function to solve Euler #2 in Javascript for adding all the even Fibonacci numbers up to 4,000,000. However, when I run my function, the chrome dev tool keeps giving me zero as the answer. I am not sure why.
function DoEverything() {
oldnum = 0;
num = 1;
total = 0;
result = addFibNumbers(num, oldnum);
console.log(result);
}
function addFibNumbers(num, oldnum) {
while(num < 4000000) {
if (num % 2 == 0) {
newnum = num + oldnum;
total += newnum;
oldnum = num;
num = newnum;
}
return total;
}
}
DoEverything();
The reason its returning 0:
result = addFibNumbers(num, oldnum);//num=1,oldNum=0
//function
while(num < 4000000) { //num is 1, so it enters while
if (num % 2 == 0) {// 1 % 2 == 1, so skip this if
return total;// this ends the function, returning total=0 as nothing was changed
I guess you are looking to do this:
while(num < 4000000) {
newnum = num + oldnum;
if (newnum % 2 == 0 && newnum < 4000000) {
total += newnum;
}
oldnum = num;
num = newnum;
}
return total;
I would guess it is your while loop
Change this:
while(num < 4000000) {
if (num % 2 == 0) {
newnum = num + oldnum;
total += newnum;
oldnum = num;
num = newnum;
}
return total;
}
to this:
while(num < 4000000) {
if (num % 2 == 0) {
newnum = num + oldnum;
total += newnum;
oldnum = num;
num = newnum;
}
}
return total;
Your while loop is useless with a return in it and no if statement to control it's use.
In addition to modifying your while statement inside of addFibNumbers() like so:
function addFibNumbers(num, oldnum) {
while(num < 4000000) {
newnum = oldnum + num;
if (oldnum % 2 == 0) {
total += oldnum;
}
oldnum = num;
num = newnum;
}
return total;
}
you will also need to initialize the first two Fibonacci terms to 1 and 2:
oldnum = 1; and num = 2;

FizzBuzz program (details given) in Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Can someone please correct this code of mine for FizzBuzz? There seems to be a small mistake. This code below prints all the numbers instead of printing only numbers that are not divisible by 3 or 5.
Write a program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
function isDivisible(numa, num) {
if (numa % num == 0) {
return true;
} else {
return false;
}
};
function by3(num) {
if (isDivisible(num, 3)) {
console.log("Fizz");
} else {
return false;
}
};
function by5(num) {
if (isDivisible(num, 5)) {
console.log("Buzz");
} else {
return false;
}
};
for (var a=1; a<=100; a++) {
if (by3(a)) {
by3(a);
if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log("\n");
}
} else if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log(a+"\n")
}
}
for (let i = 1; i <= 100; i++) {
let out = '';
if (i % 3 === 0) out += 'Fizz';
if (i % 5 === 0) out += 'Buzz';
console.log(out || i);
}
/*Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”*/
var str="",x,y,a;
for (a=1;a<=100;a++)
{
x = a%3 ==0;
y = a%5 ==0;
if(x)
{
str+="fizz"
}
if (y)
{
str+="buzz"
}
if (!(x||y))
{
str+=a;
}
str+="\n"
}
console.log(str);
Your functions return falsy values no matter what, but will print anyway. No need to make this overly complicated.
fiddle: http://jsfiddle.net/ben336/7c9KN/
Was fooling around with FizzBuzz and JavaScript as comparison to C#.
Here's my version, heavily influenced by more rigid languages:
function FizzBuzz(aTarget) {
for (var i = 1; i <= aTarget; i++) {
var result = "";
if (i%3 === 0) result += "Fizz";
if (i%5 === 0) result += "Buzz";
if (result.length ===0) result = i;
console.log(result);
}
}
I like the structure and ease of read.
Now, what Trevor Dixon cleverly did is relay on the false-y values of the language (false , null , undefined , '' (the empty string) , 0 and NaN (Not a Number)) to shorten the code.
Now, the if (result.length ===0) result = i; line is redundant and the code will look like:
function FizzBuzz(aTarget) {
for (var i = 1; i <= aTarget; i++) {
var result = "";
if (i%3 === 0) result += "Fizz";
if (i%5 === 0) result += "Buzz";
console.log(result || i);
}
}
Here we relay on the || operator to say : "if result is false, print the iteration value (i)". Cool trick, and I guess I need to play more with JavaScript in order to assimilate this logic.
You can see other examples (from GitHub) that will range from things like :
for (var i=1; i <= 20; i++)
{
if (i % 15 == 0)
console.log("FizzBuzz");
else if (i % 3 == 0)
console.log("Fizz");
else if (i % 5 == 0)
console.log("Buzz");
else
console.log(i);
}
No variables here, and just check for division by 15,3 & 5 (my above one only divides by 3 & 5, but has an extra variable, so I guess it's down to microbenchmarking for those who care, or style preferences).
To:
for(i=0;i<100;)console.log((++i%3?'':'Fizz')+(i%5?'':'Buzz')||i)
Which does it all in on line, relaying on the fact that 0 is a false value, so you can use that for the if-else shorthanded version (? :), in addition to the || trick we've seen before.
Here's a more readable version of the above, with some variables:
for (var i = 1; i <= 100; i++) {
var f = i % 3 == 0, b = i % 5 == 0;
console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}
All in all, you can do it in different ways, and I hope you picked up some nifty tips for use in JavaScript :)
.fizz and .buzz could be CSS classes, no? In which case:
var n = 0;
var b = document.querySelector("output");
window.setInterval(function () {
n++;
b.classList[n%3 ? "remove" : "add"]("fizz");
b.classList[n%5 ? "remove" : "add"]("buzz");
b.textContent = n;
}, 500);
output.fizz:after {
content: " fizz";
color:red;
}
output.buzz:after {
content: " buzz";
color:blue;
}
output.fizz.buzz:after {
content: " fizzbuzz";
color:magenta;
}
<output>0</output>
With ternary operator it is much simple:
for (var i = 0; i <= 100; i++) {
str = (i % 5 == 0 && i % 3 == 0) ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0) ? "Buzz" : i);
console.log(str);
}
for(i = 1; i < 101; i++) {
if(i % 3 === 0) {
if(i % 5 === 0) {
console.log("FizzBuzz");
}
else {
console.log("Fizz");
}
}
else if(i % 5 === 0) {
console.log("Buzz");
}
else {
console.log(i)
}
}
In your by3 and by5 functions, you implicitly return undefined if it is applicable and false if it's not applicable, but your if statement is testing as if it returned true or false. Return true explicitly if it is applicable so your if statement picks it up.
As an ES6 generator: http://www.es6fiddle.net/i9lhnt2v/
function* FizzBuzz() {
let index = 0;
while (true) {
let value = ''; index++;
if (index % 3 === 0) value += 'Fizz';
if (index % 5 === 0) value += 'Buzz';
yield value || index;
}
}
let fb = FizzBuzz();
for (let index = 0; index < 100; index++) {
console.log(fb.next().value);
}
Codeacademy sprang a FizzBuzz on me tonight. I had a vague memory that it was "a thing" so I did this. Not the best way, perhaps, but different from the above:
var data = {
Fizz:3,
Buzz:5
};
for (var i=1;i<=100;i++) {
var value = '';
for (var k in data) {
value += i%data[k]?'':k;
}
console.log(value?value:i);
}
It relies on data rather than code. I think that if there is an advantage to this approach, it is that you can go FizzBuzzBing 3 5 7 or further without adding additional logic, provided that you assign the object elements in the order your rules specify. For example:
var data = {
Fizz:3,
Buzz:5,
Bing:7,
Boom:11,
Zing:13
};
for (var i=1;i<=1000;i++) {
var value = '';
for (var k in data) {
value += i%data[k]?'':k;
}
console.log(value?value:i);
}
This is what I wrote:
for (var num = 1; num<101; num = num + 1) {
if (num % 5 == 0 && num % 3 == 0) {
console.log("FizzBuzz");
}
else if (num % 5 == 0) {
console.log("Buzz");
}
else if (num % 3 == 0) {
console.log("Fizz");
}
else {
console.log(num);
}
}
for (var i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) console.log("FizzBuzz");
else if (i%3 === 0) console.log("Fizz");
else if (i%5 === 0) console.log("Buzz");
else console.log(i);
}
One of the easiest way to FizzBuzz.
Multiple of 3 and 5, at the same time, means multiple of 15.
Second version:
for (var i = 1; i <= 100; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i%3 === 0) console.log("Fizz");
else if (i%5 === 0) console.log("Buzz");
else console.log(i);
}
In case someone is looking for other solutions: This one is a pure, recursive, and reusable function with optionally customizable parameter values:
const fizzBuzz = (from = 1, till = 100, ruleMap = {
3: "Fizz",
5: "Buzz",
}) => from > till || console.log(
Object.keys(ruleMap)
.filter(number => from % number === 0)
.map(number => ruleMap[number]).join("") || from
) || fizzBuzz(from + 1, till, ruleMap);
// Usage:
fizzBuzz(/*Default values*/);
The from > till is the anchor to break the recursion. Since it returns false until from is higher than till, it goes to the next statement (console.log):
Object.keys returns an array of object properties in the given ruleMap which are 3 and 5 by default in our case.
Then, it iterates through the numbers and returns only those which are divisible by the from (0 as rest).
Then, it iterates through the filtered numbers and outputs the saying according to the rule.
If, however, the filter method returned an empty array ([], no results found), it outputs just the current from value because the join method at the end finally returns just an empty string ("") which is a falsy value.
Since console.log always returns undefined, it goes to the next statement and calls itself again incrementing the from value by 1.
A Functional version of FizzBuzz
const dot = (a,b) => x => a(b(x));
const id = x => x;
function fizzbuzz(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dot(f(3, 'fizz'), f(5, 'buzz')) (id) (n);
}
for more options in the above replace dot with dots as below
const dots = (...a) => f0 => a.reduceRight((acc, f) => f(acc), f0);
function fizzbuzz(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dots(f(3, 'fizz'), f(5, 'buzz'), f(7, 'bam')) (id) (n);
}
Reference: FizzBuzz in Haskell by Embedding a Domain-Specific Language
by Maciej Piro ́g
for (i=1; i<=100; i++) {
output = "";
if (i%5==0) output = "buzz";
if (i%3==0) output = "fizz" + output;
if (output=="") output = i;
console.log(output);
}
Functional style! JSBin Demo
// create a iterable array with a length of 100
// and map every value to a random number from 1 to a 100
var series = Array.apply(null, Array(100)).map(function() {
return Math.round(Math.random() * 100) + 1;
});
// define the fizzbuzz function which takes an interger as input
// it evaluates the case expressions similar to Haskell's guards
var fizzbuzz = function (item) {
switch (true) {
case item % 15 === 0:
console.log('fizzbuzz');
break;
case item % 3 === 0:
console.log('fizz');
break;
case item % 5 === 0:
console.log('buzz');
break;
default:
console.log(item);
break;
}
};
// map the series values to the fizzbuzz function
series.map(fizzbuzz);
Another solution, avoiding excess divisions and eliminating excess spaces between "Fizz" and "Buzz":
var num = 1;
var FIZZ = 3; // why not make this easily modded?
var BUZZ = 5; // ditto
var UPTO = 100; // ditto
// and easily extended to other effervescent sounds
while (num < UPTO)
{
var flag = false;
if (num % FIZZ == 0) { document.write ("Fizz"); flag = true; }
if (num % BUZZ == 0) { document.write ("Buzz"); flag = true; }
if (flag == false) { document.write (num); }
document.write ("<br>");
num += 1;
}
If you're using using jscript/jsc/.net, use Console.Write(). If you're using using Node.js, use process.stdout.write(). Unfortunately, console.log() appends newlines and ignores backspaces, so it's unusable for this purpose. You could also probably append to a string and print it. (I'm a complete n00b, but I think (ok, hope) I've been reasonably thorough.)
"Whaddya think, sirs?"
check this out!
function fizzBuzz(){
for(var i=1; i<=100; i++){
if(i % 3 ===0 && i % 5===0){
console.log(i+' fizzBuzz');
} else if(i % 3 ===0){
console.log(i+' fizz');
} else if(i % 5 ===0){
console.log(i+' buzz');
} else {
console.log(i);
}
}
}fizzBuzz();
Slightly different implementation.
You can put your own argument into the function. Can be non-sequential numbers like [0, 3, 10, 1, 4]. The default set is only from 1-15.
function fizzbuzz (set) {
var set = set ? set : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
var isValidSet = set.map((element) => {if (typeof element !== 'number') {return false} else return true}).indexOf(false) === -1 ? true : false
var gotFizz = (n) => {if (n % 3 === 0) {return true} else return false}
var gotBuzz = (n) => {if (n % 5 === 0) {return true} else return false}
if (!Array.isArray(set)) return new Error('First argument must an array with "Number" elements')
if (!isValidSet) return new Error('The elements of the first argument must all be "Numbers"')
set.forEach((n) => {
if (gotFizz(n) && gotBuzz(n)) return console.log('fizzbuzz')
if (gotFizz(n)) return console.log('fizz')
if (gotBuzz(n)) return console.log('buzz')
else return console.log(n)
})
}
var num = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var runLoop = function() {
for (var i = 1; i<=num.length; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
}
else if (i % 5 === 0) {
console.log("Buzz");
}
else if (i % 3 === 0) {
console.log("Fizz");
}
else {
console.log(i);
}
}
};
runLoop();
Just want to share my way to solve this
for (i = 1; i <= 100; i++){
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzBuzz');
} else if (i % 3 === 0) {
console.log('fizz');
} else if (i % 5 === 0){
console.log('buzz');
} else {
console.log(i);
}
}
var limit = prompt("Enter the number limit");
var n = parseInt(limit);
var series = 0;
for(i=1;i<n;i++){
series = series+" " +check();
}
function check() {
var result;
if (i%3==0 && i%5==0) { // check whether the number is divisible by both 3 and 5
result = "fizzbuzz "; // if so, return fizzbuzz
return result;
}
else if (i%3==0) { // check whether the number is divisible by 3
result = "fizz "; // if so, return fizz
return result;
}
else if (i%5==0) { // check whether the number is divisible by 5
result = "buzz "; // if so, return buzz
return result;
}
else return i; // if all the above conditions fail, then return the number as it is
}
alert(series);
Thats How i did it :
Not the best code but that did the trick
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for(var i = 0 ; i <= 19 ; i++){
var fizz = numbers[i] % 3 === 0;
var buzz = numbers[i] % 5 === 0;
var fizzBuzz = numbers[i] % 5 === 0 && numbers[i] % 3 === 0;
if(fizzBuzz){
console.log("FizzBuzz");
} else if(fizz){
console.log("Fizz");
} else if(buzz){
console.log("Buzz");
} else {
console.log(numbers[i]);
}
}
As much as this is easy logic it can be a daunting task for beginners. Below is my solution to the FizzBuzz problem:
let i = 1;
while(i<=100){
if(i % 3 ==0 && i % 5 == 0){
console.log('FizzBuzz');
}
else if(i % 3 == 0){
console.log('Fizz');
}
else if(i % 5 == 0){
console.log('Buzz');
}
else{
console.log(i);
}
i++;
}
considering performance and readability, please find my take on this problem
way 1: instead of doing a math modules operation in an if loop, which results in performing 3 times taking it a step above reduces the overhead
function fizzBuzz(n) {
let count =0;
let x = 0;
let y = 0;
while(n!==count)
{
count++;
x = count%3;
y = count%5;
if(x === 0 && y ===0)
{
console.log("fizzbuzz");
}
else if(x === 0)
{
console.log("fizz");
}
else if(y === 0)
{
console.log("buzz");
}
else
{
console.log(count);
}
}
}
fizzBuzz(15);
way 2: condensing the solution
function fizzBuzz(n) {
let x = 0;
let y = 0;
for (var i = 1; i <= n; i++) {
var result = "";
x = i%3;
y = i%5;
if (x === 0 && y === 0) result += "fizzbuzz";
else if (x === 0) result += "fizz";
else if (y === 0) result += "buzz";
console.log(result || i);
}
}
fizzBuzz(5)
Here's my favorite solution. Succinct, functional & fast.
const oneToOneHundred = Array.from({ length: 100 }, (_, i) => i + 1);
const fizzBuzz = (n) => {
if (n % 15 === 0) return 'FizzBuzz';
if (n % 3 === 0) return 'Fizz';
if (n % 5 === 0) return 'Buzz';
return n;
};
console.log(oneToOneHundred.map((i) => fizzBuzz(i)).join('\n'));
function fizzBuzz(n) {
for (let i = 1; i < n + 1; i++) {
if (i % 15 == 0) {
console.log("fizzbuzz");
} else if (i % 3 == 0) {
console.log("fizz");
} else if (i % 5 == 0) {
console.log("buzz");
} else {
console.log(i);
}
}
}
fizzBuzz(15);
Different functional style -- naive
fbRule = function(x,y,f,b,z){return function(z){return (z % (x*y) == 0 ? f+b: (z % x == 0 ? f : (z % y == 0 ? b: z))) }}
range = function(n){return Array.apply(null, Array(n)).map(function (_, i) {return i+1;});}
range(100).map(fbRule(3,5, "fizz", "buzz"))
or, to incorporate structures as in above example: ie [[3, "fizz"],[5, "buzz"], ...]
fbRule = function(fbArr,z){
return function(z){
var ed = fbArr.reduce(function(sum, unit){return z%unit[0] === 0 ? sum.concat(unit[1]) : sum }, [] )
return ed.length>0 ? ed.join("") : z
}
}
range = function(n){return Array.apply(null, Array(n)).map(function (_, i) {return i+1;});}
range(100).map(fbRule([[3, "fizz"],[5, "buzz"]]))
OR, use ramda [from https://codereview.stackexchange.com/questions/108449/fizzbuzz-in-javascript-using-ramda ]
var divisibleBy = R.curry(R.compose(R.equals(0), R.flip(R.modulo)))
var fizzbuzz = R.map(R.cond([
[R.both(divisibleBy(3), divisibleBy(5)), R.always('FizzBuzz')],
[divisibleBy(3), R.aklways('Fizz')],
[divisibleBy(5), R.always('Buzz')],
[R.T, R.identity]
]));
console.log(fizzbuzz(R.range(1,101)))

Count the prime numbers from 2 to 100 with simpler code than this

It has to be with just functions, variables, loops, etc (Basic stuff). I'm having trouble coming up with the code from scratch from what I've I learned so far(Should be able to do it). Makes me really mad :/. If you could give me step by step to make sure I understand I'd really really appreciated. Thanks a bunch in advanced.
How could I get the same result with a simpler code than this one:
var primes=4;
for (var counter = 2; counter <= 100; counter = counter + 1)
{
var isPrime = 0;
if(isPrime === 0){
if(counter === 2){console.log(counter);}
else if(counter === 3){console.log(counter);}
else if(counter === 5){console.log(counter);}
else if(counter === 7){console.log(counter);}
else if(counter % 2 === 0){isPrime=0;}
else if(counter % 3 === 0){isPrime=0;}
else if(counter % 5 === 0){isPrime=0;}
else if(counter % 7 === 0){isPrime=0;}
else {
console.log(counter);
primes = primes + 1;
}
}
}
console.log("Counted: "+primes+" primes");
I'm feeling naughty today so:
function printPrimesBetweenTwoAndOneHundredSimply(){
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97],
i,
arrayLength = primes.length;
for(i = 0; i < arrayLength; i++){
console.log(primes[i]);
}
console.log("Counted: " + arrayLength + " primes");
}
First, you really don't need to use === for this. The standard == will suffice. Second, you can make all of those lines that are the same thing, except for a single digit into one line:
var primes=4;
for (var counter = 2; counter <= 100; counter = counter + 1)
{
var isPrime = 0;
if(isPrime == 0){
if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
else if(counter % 2 == 0 || counter % 3 == 0 || counter % 5 == 0 || counter % 7 == 0)isPrime=0;
else {
console.log(counter);
primes = primes + 1;
}
}
}
console.log("Counted: "+primes+" primes");
You'll also notice that the {} was removed on a few lines. This is because a single line of code following an if (among others) is always considered nested.
Next, we can change your primes = primes + 1; to this: primes++; which just tells primes to increment itself by one. The same can be done for your counter. We also know that isPrime equals "0" because you set it to that a second ago, so we no longer need that if statement:
var primes=4;
for (var counter = 2; counter <= 100; counter++)
{
var isPrime = 0;
if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
else if(counter % 2 == 0 || counter % 3 == 0 || counter % 5 == 0 || counter % 7 == 0)isPrime=0;
else {
console.log(counter);
primes++;
}
}
console.log("Counted: "+primes+" primes");
Next, we can do a negative check (!= instead of ==) on the values and combine your else if with your else. Since we're doing a negative check (for this case) we have to switch the ORs (||) to ANDs (&&):
var primes=4;
for (var counter = 2; counter <= 100; counter++)
{
if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
else if(counter % 2 != 0 && counter % 3 != 0 && counter % 5 != 0 && counter % 7 != 0) {
console.log(counter);
primes++;
}
}
console.log("Counted: "+primes+" primes");
There are many other ways to write it, but I felt it more beneficial to you to use what you started with and shorten it from there.
This finds all prime numbers between 2 and 100:
var primes=0;
var isprime = true;
for (var counter = 2; counter <= 100; counter = counter + 1)
{
// For now, we believe that it is a prime
isprime = true;
var limit = Math.round(Math.sqrt(counter)); // See comment from #AresAvatar, below
// We try to find a number between 2 and limit that gives us a reminder of 0
for (var mod = 2; mod <= limit; mod++) {
// If we find one, we know it's not a prime
if (counter%mod == 0) {
isprime = false;
break; // Break out of the inner for loop
}
}
if (isprime) {
console.log(counter, limit);
primes = primes + 1;
}
}
console.log("Counted: "+primes+" primes");
Of course "simpler" is not defined. :-)
The following can be made much shorter, but has a bit of robustness built in.
// Get primes from 0 to n.
// n must be < 2^53
function primeSieve(n) {
n = Number(n);
if (n > Math.pow(2, 53) || isNaN(n) || n < 1) {
return;
}
var primes = [];
var notPrimes = {};
var num;
for (var i=2; i<n; i++) {
for (var j=2; j<n/2; j++) {
num = i*j;
notPrimes[num] = num;
}
if (!(i in notPrimes)) {
primes.push(i);
}
}
return primes
}
So if you want less code:
// Get primes from 0 to n.
// n must be < 2^53
function primeSieve2(n) {
var primes = [], notPrimes = {};
for (var i=2; i<n; i++) {
for (var j=2; j<n/2; j++)
notPrimes[i*j] = i*j;
i in notPrimes? 0 : primes.push(i);
}
return primes
}
This is pretty simple (I mean, short):
console.log(2); console.log(3);
var m5=25, m7=49, i=5, d=2, c=2;
for( ; i<100; i+=d, d=6-d )
{
if( i!=m5 && i!=m7) { console.log(i); c+=1; }
if( m5 <= i ) m5+=10;
if( m7 <= i ) m7+=14;
}
c
It is an "unrolled" sieve of Eratosthenes with 2-3-wheel factorization.
On the one hand, we enumerate all the numbers below 100 (and bigger than 3) that are coprime with 2 and 3, as partial sums of 5+2+4+2+4+... , so that there are no multiples of 2 and 3 among thus enumerated numbers.
On the other hand, we discard from among them all the multiples of 5 and 7, by enumerating them as partial sums of 25+10+10+10+... and 49+14+14+14+... . Multiples of 2 and 3 are not there in the first place, and the first multiple of 11 that needs to be discarded by the sieve of Eratosthenes is 121.
This will be simpler for your Question....
for (int i = 2; i < 100; i++) {
int j = 0;
for (j = 2; j < i; j++)
if ((i % j) == 0)break;
if (i == j)
System.out.print(" " + i);}

Categories