How to stop this for-loop? - javascript

var number = prompt("Typ some numbers:")
var som = 0
for (var x = 0; x < number.length; x++) {
if (!(number[x] === 0)) {
if ((number[x] % 2) === 1) {
som += (number[x] * number[x])
}
} else {
break;
}
}
alert(som)
I want to type some random numbers (0-9) and then it must say the som of the Square of all the odd numbers before I type zero. For example I type: 5903. 5*5 + 9*9 = 106. So AFTER I type a zero it must STOP the for loop of going further. But right now if I typ 5903 it says 115, so right now it still DOES count 3*3 extra. So how do I make it stop after I type a zero? It doesn't work right now, it goes on after I type a zero. Someone know what's the problem? Maybe syntax?

Please change
if (!(number[x] === 0)) {
to
if (number[x] !== '0') {
because you are comparing strings.
Working example:
var number = prompt("Typ some numbers:"),
som = 0;
for (var x = 0; x < number.length; x++) {
if (number[x] !== '0') {
if ((number[x] % 2) === 1) {
som += (number[x] * number[x]);
}
} else {
break;
}
}
alert(som);

you are checking if the number is equal to 0, but your number is actually '0'
you need to parse the input as an integer or you can use double equals
var number = prompt("Typ some numbers:");
var som = 0;
for (var x = 0; x < number.length; x++){
if(number[x] == 0){
break;
}
if ((number[x] % 2) === 1) {
som += (number[x] * number[x]);
}
}
alert(som);

Related

how to get an output of next `ten` odd and even numbers after entering any random number in javascript

I want to have a logic where if I enter an even number I want next 10 even numbers to be printed and If I enter an odd number, I want next 10 odd numbers to be printed. How should I rectify this logic inside a function. If someone can please help me rectifying the logic which was answered.
JS
function oddEven() {
var input = prompt("");
for (let x = 1; x <= 10; x++) {
console.log(input + x * 2);
}
}
oddEven()
This should work for any number
const input = 2
for (let x = 1; x <= 10; x += 1) {
console.log(input + x * 2)
}
i hope this help
function printTen(input){
let list = []
let number = input
while(list.length <= 10){
number++
if(input % 2 === 0 && number % 2 === 0){
console.log(number + " is even");
list.push(number)
}else if(input % 2 !== 0 && number % 2 !== 0) {
console.log(number + " is odd");
list.push(number)
}
}
}
printTen(9)
let inputval = 2;
for (let x = 1; x <= 10; x++) {
console.log(inputval + x * 2)
}

javascript multiplication table order

I have the followign school project:
You enter a number into a prompt
Highlights every occurance of numbers in interval [1; 100] that are the multiplicator of the inputted number.
Issue is, whenever I input a number dividable by /5 it ruins the table formatting with the extra <br/>
<html>
<body>
<script>
var y = prompt("enter a number between 1 -100 ")
if( y<=100 && y>=1 ){
for (i = 1 ; i<=100 ; i++){
var idk = i + " "
if (i%y!=0){
document.write(idk)
}
if(i%10==0 ){
document.write("</br>" )
console.log(i)
}
if(i%y==0){
document.write(idk.fontcolor("red"))
}
}
}
else {
document.write("your number isnt good")
}
</script>
</body>
this is my code can someone help me fix it
That's because of the order of your if conditions.
If your number is divided by 5, it also by 10. Re-arrange the code structure, so you check for color-ins first and only then apply <br/> like so. (even then, it is a kind of ugly conditional though)
Basically , just moved if (i % y == 0) {} above if (i % 10 == 0) {}
let y = prompt("enter a number between 1 -100 ")
if (y <= 100 && y >= 1) {
for (let i = 1; i <= 100; i++) {
let idk = i + " "
if (i % y != 0) {
document.write(idk)
}
if (i % y == 0) {
document.write(idk.fontcolor("red"))
}
if (i % 10 == 0) {
document.write("</br>")
}
}
} else {
document.write("your number isnt good")
}

Greatest Prime Factor

I'm trying to complete an algorithm challenge to find the largest prime factor of 600851475143. I'm not necessarily asking for the answer. Just trying to figure out why this code isn't working. Why does it return 'undefined' instead of a number?
let isPrime = n => {
let div = n - 1;
while (div > 1) {
if (n % div == 0) return false;
div--;
}
return true;
};
let primeFactor = x => {
for (let i = Math.floor(x / 2); i > 1; i--) {
if (x % i == 0 && isPrime(i) == true) {
return i;
}
}
};
console.log(primeFactor(35)); // 7
console.log(primeFactor(13195)); // 29
console.log(primeFactor(600851475143)); // undefined
The problem is not your algorithm it is perfectly valid, check the below slightly modified algorithm, all I've done is replaced your starting point Math.floor(x/2) with a parameter that you can choose:
let isPrime = n => {
let div = n - 1;
while (div > 1) {
if (n % div == 0) return false;
div--;
}
return true;
};
function primeFactor(x, n){
for (let i = n; i > 1; i--) {
if (x % i == 0 && isPrime(i) == true) {
return i;
}
}
}
console.log(primeFactor(35, 35));
console.log(primeFactor(13195, 13195));
console.log(primeFactor(600851475143, 100000))
Using the above you'll get an answer that proves your implementation works, but the loop is too big to do the entire thing(i.e. from Math.floor(600851475143/2)). Say your computer can do 500million loops per second, going through every one from 300,425,737,571 down to 1 would take 167 hours, even at 5 billion loops per second it would take 16 and a half hours. Your method is extremely inefficient but will return the correct answer. The reason you're not getting an answer on JSBin is more likely to do with browser/service limitations.
Spoilers on more efficient solution below
The following implementation uses a prime sieve(Sieve of Eratosthenes) in order to generate any list of primes requested and then checks if they fully factor into the given number, as long as you use a large enough list of primes, this will work exactly as intended. it should be noted that because it generates a large list of primes it can take some time if ran incorrectly, a single list of primes should be generated and used for all calls below, and the cached list of primes will pay off eventually by having to perform less calculations later on:
function genPrimes(n){
primes = new Uint32Array(n+1);
primes.fill(1)
for(var i = 2; i < Math.sqrt(n); i++){
if(primes[i]){
for(var j = 2*i; j < n; j+=i){
primes[j] = 0;
}
}
}
primeVals = []
for(var i = 2; i < primes.length; i++){
if(primes[i]){
primeVals.push(i);
}
}
return primeVals;
}
function primeFactor(x, primes){
var c = x < primes.length ? x : primes.length
for (var i = c; i > 1; i--) {
if(x % primes[i] == 0){
return primes[i];
}
}
}
primes = genPrimes(15487457);
console.log(primeFactor(35, primes));
console.log(primeFactor(13195, primes));
console.log(primeFactor(600851475143, primes));
console.log(primeFactor(30974914,primes));
let primeFactor = x => {
if (x === 1 || x === 2) {
return x;
}
while (x % 2 === 0) {
x /= 2;
}
if (x === 1) {
return 2;
}
let max = 0;
for (let i = 3; i <= Math.sqrt(x); i += 2) {
while (x % i === 0) {
x /= i;
max = Math.max(i, max);
}
}
if (x > 2) {
max = Math.max(x, max);
}
return max;
};
console.log(primeFactor(35));
console.log(primeFactor(13195));
console.log(primeFactor(27));
console.log(primeFactor(1024));
console.log(primeFactor(30974914));
console.log(primeFactor(600851475143));
Optimizations
Dividing the number by 2 until it's odd since no even number is prime.
The iteration increment is 2 rather than 1 to skip all even numbers.
The iteration stops at sqrt(x). The explanation for that is here.

parseFloat.toPreceision just adds zeros

I'm sending the number/string 0.001 to a the function below:
SignificantFigures = 4;
function LimitNumberOfDigits(num) {
var tempStr = "";
if (isNaN(num))
return "\xD8";
else{
if (parseFloat(num) === 0 || (num.toString().indexOf('.') === -1 && parseInt(num) < 9999) || num.toString().length <= 4) {
return num;
}
tempStr = parseFloat(num).toPrecision(SignificantFigures);
if (tempStr.indexOf("e") > -1) {
var startE = tempStr.indexOf("e");
var endE = 0;
for (var i = startE +2 ; i < tempStr.length; i++ ) { // + to ignore e and sign (+ or - )
if(parseInt(tempStr[i], 10) > 0) {
endE = i;
}else {
break;
}
}
if (startE + 2 === endE) {
var pow = tempStr[endE];
} else {
var pow = tempStr.substring(startE +2 ,endE);
}
return tempStr.substring(0,startE) + "*10<sup>"+ pow +"</sup>";
}else {
return parseFloat(num).toPrecision(SignificantFigures);
}
}
}
When im sending 0.2 or even 0.11 im getting like 0.2000 and 0.1100.
The issue here is the toPrecision acts like ToFixed.
Ideas?
EDIT
What i want? simple as that, if a numbers needs to be changed e.g 0.012312312041 it should be 0.0123 , numbers like 0.12 or 28 should stay the same.

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