Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,037 questions

40,897 answers

573 users

How to calculate sum of series 1 + 11 + 111 + 1111 + ... N in JavaScript

1 Answer

0 votes
// sum = 1 + 11 + 111 + 1111 + ... N 

function sum_of_series(N) {
    let sum = 0, tmp = 1, s = "";
    
    for (let i = 0; i < N; i++) {
        s += tmp + " ";
        if (i < N - 1) {
            s += "+ ";
        }
        sum += tmp;
        tmp = (tmp * 10) + 1;
    }
    
    console.log(s);
    
    return sum;
}
        
const N = 6;
const sum = sum_of_series(N);

console.log("= " + sum);




/*
run:
   
1 + 11 + 111 + 1111 + 11111 + 111111 
= 123456
 
*/

 





answered Jan 17 by avibootz
...