I want to add number of every 10th element.
For example,
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var d = i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
But, I want like this
1,2,3,4,5,6,7,8,9,10,16,17,18,19,20,21,22,23,24,25,31,32,33,34,35,36,37,38,39,40....
I want to add 5 after 10th number, add 10 after 20th number, add 15 after 30th number, add 20 after 40th number, add 25 after 50th number. I know this is simple. But, I couldn't get any result.
JsFiddle
You could take an offset and increment this value by five if the result of the index variable is dividable by ten.
var i,
offset = 0,
result = [];
for (i = 1; i <= 100; i++) {
result.push(i + offset);
if (i % 10 === 0) offset += 5;
}
console.log(result.join(' '));
You could use the modulo operator % to check if the current number (i) is a multiple of 10, then if it is, add 5 to i:
if (i % 10 === 0) {
i += 5;
}
Moreover, I recommend that you keep a string of all the numbers you want to append to your page, as querying and adding contents to the DOM each loop iteration is an expensive operation which can be avoided
See example below:
function myFunction() {
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
}
myFunction();
<div id="demo"></div>
I used a counter to account for in increment on the 10th element, and am simply putting the results on the console. Obviously there are some that would simply just add 5, the counter option is just a design preference.
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
function myFunction(arr){
var counter = 0;
for(var i = 0; i<arr.length; i++){
if (i%10 ==0){
counter++;
}
arr[i] = arr[i]+(5*(counter-1));
}
console.log(arr);
};
myFunction(arr);
Do something like:
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var j=Math.floor(i/10);
var x=5*j;
var d = x+i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Expanding on the performance issue presented by Nick Parsons
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
innerHTML is just horribly slow.
Consider the following code that employs a document fragment and the vanilla .append() method
const fragment = document.createDocumentFragment();
for (var i = 1; i <= 100; i++)
{
if( i % 10 === 0 )
i += 5;
fragment.append( document.createTextNode( i ) );
fragment.append( document.createElement('BR') );
}
document.getElementById('demo').append( fragment );
From my testing, it's about 2000(!) times faster to use a document fragment.
Change your fucntion like that:
function myFunction() {
for (var i = 1; i <= 100; i++) {
var d = i;
if (i > 1 && i % 10 === 1) {
d = (i % 10) * 5 + i;
}
document.getElementById("demo").innerHTML += d + ",";
}
}
I have solved the seventh problem of Euler, it says:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
see that the 6th prime is 13.
What is the 10 001st prime number?
I solved it using, and in the array in which I keep the cousins, when it reaches the length of 10001, I return that number. The algorithm takes 1300 ms, which I tink that is very inefficient, what am I doing particularly in my implementation?
var start = performance.now();
function eratosthenes(n) {
var arr = [2], acc = 0;
// matrix to save the found prime numbers and mark their multiples
for(var i = 3; true; i += 2) { // loop
if(arr.length === n) return arr[arr.length - 1]; // if the array length is equal to n return the last number
if(!resolve(arr, i)) { // check if is multiple of the prime numbers, already found.
arr.push(i); // if isnt multiple, save it
}
}
}
function resolve(array, n) {
return array.some(cur => !(n%cur));
}
console.log(eratosthenes(10001)); // Tooks 1300 ms
var end = performance.now();
var time = end - start;
console.log(time);
Euler sieve, Pham knows this one :) 12ms
Uchu, I don't see where your code is marking the multiples. Isn't that what Sieve of Eratosthenes is supposed to do?
JavaScript code (this code is actually an adaptation of code by btilly, optimizing an idea of mine):
var start = performance.now();
n = 115000
a = new Array(n+1)
total = 0
s = []
p = 1
count = 0
while (p < n){
p = p + 1
if (!a[p]){
count = count + 1
if (count == 10001){
console.log(p);
end = performance.now();
time = end - start;
console.log(time);
break;
}
a[p] = true
s.push(p)
limit = n / p
new_s = []
for (i of s){
j = i
while (j <= limit){
new_s.push(j)
a[j*p] = true;
j = j * p
}
}
s = new_s
}
}
As requested by JaromandaX, this is the code for Sieve of Eratosthenes. 51 ms on my browser (OP solution is 750 ms)
var max = 1000000;
function eratosthenes(n) {
var arr = [], count = 0;
for (var i = 0; i < max; i++){
arr.push(true);
}
for (var i = 2; i < max; i++){
if(arr[i]){
count++;
if(count == n){
return i;
}
for (var j = i + i; j < max; j += i ){
arr[j] = false;
}
}
}
}
var start = performance.now();
console.log(eratosthenes(10001));
var end = performance.now();
var time = end - start;
console.log(time);
This has a similar running time to גלעד ברקן's answer (actually about 10% faster on my machine), but doesn't rely on knowing an approximate max before starting. It performs a seive of Eratosthenes up to max (starting at 2) and then doubles max, initialises the new elements in the array per the previously found primes and repeats.
function eratosthenes(n) {
let prev_max = 1, max = 2, i, j;
const primes = [], is_prime = new Array(max+1).fill(true);
while( true ) {
for ( i = prev_max + 1; i <= max; i++){
if ( ! is_prime[i] ) continue;
primes.push( i );
if ( primes.length === n )
return i;
for ( j = i + i; j <= max; j += i )
is_prime[j] = false;
}
const next_max = max*2;
is_prime.length = next_max + 1;
is_prime.fill( true, max + 1, next_max );
for ( i = 0; i < primes.length; i++ ) {
const prime = primes[i];
for ( j = max + prime - max%prime; j <= next_max; j += prime )
is_prime[j] = false;
}
prev_max = max;
max = next_max;
}
}
var start = performance.now();
console.log(eratosthenes(10001));
var end = performance.now();
var time = end - start;
console.log(time);
If it is a code-writing exercise, it is better to explore the earlier answers.
But if you are after a simple and fast solution, here's how you can solve it using prime-lib, which I created:
import {generatePrimes} from 'prime-lib';
const seekIndex = 10_001; // index of the prime being sought
const start = Date.now();
let a, c = 0;
const i = generatePrimes({boost: seekIndex + 1});
while ((a = i.next()) && !a.done && c++ < seekIndex) ;
console.log(`Prime: ${a.value}, took ${Date.now() - start}ms`);
On my PC it spits out:
Prime: 104759, took 5ms
And with the modern RXJS this becomes even simpler still:
import {generatePrimes} from 'prime-lib';
import {from, last} from 'rxjs';
const seekIndex = 10_001; // index of the prime being sought
const i = generatePrimes({boost: seekIndex + 1});
from(i).pipe(last()).subscribe(console.log);
//=> 104759
I am not sure how to phrase this, so please re-title this question if it doesn't make sense. Anyways, this is what I am trying to do.
I have a variable with the length of 9.
And then I have another variable with the length of 3.
How do I write a loop that iterates through all 9 but starts over every third time?
For example: I have this,
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i + 1);
}
output = 1,2,3,4,5,6,7,8,9
The output I want to create
output = 1,2,3,1,2,3,1,2,3
I was thinking there might be away to do this with an if statement or possibly modulus, but wasn't quite sure how to implement it. What would be a good way to do this? Thanks in advance.
Embrace the modulus:
function expand(length, loop_length) {
for (var i = 0; i < length; i++) {
console.log(i % loop_length + 1);
}
}
expand(9, 3) // => 1, 2, 3, 1, 2, 3, 1, 2, 3
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i % x + 1);
}
output = 1,2,3,1,2,3,1,2,3
See it in action here: http://jsfiddle.net/BgBGL/
If you want to loop from a min value to a max value a specific number of times, the easiest way is just to have 2 loops, like this:
var min = 1, max = 3, times = 3;
for (var i = 0; i < times; i++) {
for (var j = min; j <= max; j++) {
console.log(j);
}
}
Or if you want to fix total length of the sequence, then yes, you can do it with a single loop and a little bit of math:
var min = 1, max = 3, totalLength = 9;
for (var i = 0; i < totalLength; i++) {
console.log((i % (max - min + 1)) + min);
}
For that case, this works:
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
var num=(i %(x+1)) || 1;
console.log(num);
}
You could go mad with following syntax:
var i = 0;
do {
console.log(i++ % 3 + 1);
} while (i < 9);
Alternative, you could define 3 and 9 as a variable also.
I took an advantage of the fact that calling i++ will display old variable and increases it by 1 after, so I saved some bits!
See: fiddle example
x = 3;
l = 9;
for ( var i = 0; i <= l; i++)
{
for ( var j = 1; j <= x; j++)
{
console.log(j);
}
}
I am filling an array with random numbers with a loop, but the random number is exactly the same for each item in the array, I think this is because of the seed value that Math.rand() uses. How can i get a different number each time?
for(var i = 0; i < 10; i++){
number[i] = getRandom(0, 100);
}
function getRandom(a, b){
var num = Math.floor((Math.random()*b)+a);
return num;
}
Works fine for me:
http://jsfiddle.net/kzUUt/
You need to declare number though...
var number = new Array(10);
for(var i = 0; i < 10; i++)
{
number[i] = getRandom(0, 100);
console.log(number[i]);
}
function getRandom(a, b)
{
var num = Math.floor((Math.random()*b)+a);
return num;
}
Here is working demo.
var number = new Array();
for (var i = 0; i < 10; i++) {
number[i] = getRandom(0, 100);
}
function getRandom(a, b) {
return Math.floor((Math.random() * b) + a);
}
for (var j = 0; j < 10; j++) {
alert(number[j]);
}