 # Help with Loops 3

I finished the exercise, but I wanted to append the last item on the list differently, as with the list of cat names example in the “Looping code” article. The easy way to do it was to nest another if(i === 2) condition in there, since 2 is the last prime number on the list, but that seems cheap–I’d like to figure out how to word the condition so that it would theoretically do the same for the last item no matter what it is. How to reword line 46?

Here’s the overall task:

You need to use a loop to go through the numbers 2 to 500 backwards (1 is not counted as a prime number), and run the provided `isPrime()` function on them. For each number that isn’t a prime number, continue on to the next loop iteration. For each one that is a prime number, add it to the paragraph’s `textContent` along with some kind of separator.

1 Like

вы можете чуточку изменить свою код
for(i; i > 1; i–){
if (isPrime(i)) {
if(true) {
para.textContent += i + ‘,’;
}
}
}

Hi @bwhitstone
I created a function called startPrime that replaced the “if(i===2)” with “if(i===startPrime)”. I also needed to create a variable to know what the start number was. So all you have to do is adjust the start number. I am trying to still figure out how to automatically detect what the last number is. Might take a while. Good question by the way. This is my code which you can also find on codepen
https://codepen.io/rpieris/pen/OJbvaov

``````<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Loops: Task 3</title>
<style>
p {
color: purple;
margin: 0.5em 0;
}

* {
box-sizing: border-box;
}
</style>
<link rel="stylesheet" href="../styles.css" />
</head>

<body>

<section class="preview">

</section>

</body>
<script>
let i = 500;
let start = 14;
let firstPrime;
let para = document.createElement('p');

function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
}
}

return true;
}

// Add your code here

// find the first prime number
function startPrime(){
for (let j = start; j <= i; j++){
if (isPrime(j)) {
console.log(j)
return j;
break;
}
}
};

for(i; i > start; i--) {
if (isPrime(i)) {
if(i === startPrime()) {
para.textContent += 'and ' + i + '.';
} else {
para.textContent += i + ', ';
}
}
}

// Don't edit the code below here!
let section = document.querySelector('section');
section.appendChild(para);
</script>

</html>``````