Andy Ho
Andy Ho

Reputation: 179

project euler #1 , hacker rank

i am trying to do project euler # 1 with Javascript in HackerRank. Can someone give me a hints in what's wrong with my code. the result is always zero.

I run my function in my google chrome console, then i input processData(10), it gives me 23. I input processData(100), it gives me 2318.

When i try to use my code in the console from Hacker rank, it output the result as zero, like it didn't pass the first test which is 0.

Did anyone tried to solve some problem in hackerrank in javascript?

function processData(input) {
    var result = []
    var total=0  
    function findMultipleThreeAndFive(n){
        var i = 0;
        for(i ; i < n ;i++){      
            if(i%3 == 0 || i%5 == 0){
                result.push(i);
            }  
        }
    }
    findMultipleThreeAndFive(input)

    function sum(){

        for(var j = 0; j< result.length ;j++){
            total += result[j]
        }
        return total;
    }
    sum()

    console.log(total)
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Upvotes: 0

Views: 519

Answers (1)

Max
Max

Reputation: 2826

First off all, your code works: http://jsfiddle.net/azggks5a/ , but I thought I would show you how I would solve it:

I suggest you use ES6 sets, because they handle the uniqueness of your values.

I began by iterating through the multiples I wanted. I then multiplied the iterated multiple by every number upto belowThis. If the result was lower than belowThis I added the result to the set, otherwise I didn't.

Here's the code:

var multiplesOf = [3,5];
var belowThis = 10;
var multiples = new Set();
var totalOfMultiples = 0;

multiplesOf.forEach(function(element, index){
    for(var i=0;i<belowThis;i++) {
        if(multiplesOf[index]*i<belowThis) {
            multiples.add(multiplesOf[index]*i);
        }
    }
});

multiples.forEach(function(element, index){
    totalOfMultiples+=element;
});
console.log(totalOfMultiples);

You can change the multiples you wish to check, and to solve the question you would increase belowThis to 1000, and get a result of 233168.

Upvotes: 1

Related Questions