A
A
aleksey_vol2016-11-11 11:32:07
JavaScript
aleksey_vol, 2016-11-11 11:32:07

I rewrote the program from Pascal to JS and it doesn't work. What is the reason?

The program itself must find all integers from 1 to 300 that have five divisors.
Pascal Code

var
  i, j, k: integer;
  
begin
  for i := 2 to 300 do
  begin
    k := 0;
    for j := 2 to i do
      if (i mod j = 0)and (k < 6) then inc(k);
    if k = 5 then write(' ', i);  
  end
end.

JS code
for(i=2; i<300; i++){
  k=0;
  for(j=2; j<i; j++){
    if(i%j===0 && k<6){
      k++;
    }
  }
  if (k===5){
    alert(i);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2016-11-11
@Stalker_RED

As far as I understand, in the range 1-300, only the number 46 has five divisors, and the rest of the numbers have more or less. (And actually six, for some reason you don’t count one)
Because of the condition, if(i%j===0 && k<6)often the variable k reaches six. I changed the log output a little bit https://jsfiddle.net/Lywpupne/

M
Michael, 2016-11-11
@FFxSquall

An error in the condition in the second loop. Correct code https://jsfiddle.net/Lffjc076/
j must be not less than i, but less than or equal to. Otherwise, the number will not divide by itself and the divisors will be 4, not 5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question