Welcome to WebmasterWorld Guest from **54.198.106.21**

Forum
Moderators: **open**

joined:Apr 5, 2013

posts:1

votes: 0

Please point out the mistakes as the following code doesn't work:

<html>

<head>

<title>

Prime Numbers

</title>

</head>

<body>

<script language="javascript">

var n,i,r;

n=prompt("Enter a natural number");

i=2

while i<n

{

r=n%i

if r==0

document.write(n+"\t"+"is a composite number")

else

i++

}

document.write(n+"\t"+"is a prime number")

</script>

</body>

</html>

I had to force quit the browser after fixing enough syntax errors to make it run, but not enough to keep it from going into perpetual motion.

Grr.

I make it two fatal syntax errors, one structural error resulting in perpetual motion, plus one structural error that makes it give unintended output even when everything else works.

Anyway, you don't have to go up to n. You only need to go to

:: detour here to look up exact wording ::

Math.floor(Math.sqrt(n))

or Math.ceil depending on whether you prefer < or <=

Hee. This is just the kind of problem I would post myself, prefaced by shamefaced admission that if anyone else had asked the identical question, I would see the answer in an instant :)

While this is most certainly a homework problem, I'm going to offer the complete solution in the hopes that you're able to learn the reasoning behind it.

point out the mistakes

1. You're missing a DOCTYPE.

<!DOCTYPE html>

2. language="javascript"

That's invalid. Don't include a language attribute, instead use type="text/javascript" (which can also be omitted if you're using HTML5)

<script>

or

<script type="text/javascript">

3. i=2

Don't forget the ending semi colon:

i=2

4. while i<n

Should be

while (i < n)

5. r=n%i

r=n%i

6. if r==0

if (r==0)

7. It's good practice to always include { } around if/else cases:

if (r==0) {

...

}

else {

...

}

8. Avoid using document.write

Generally, it's bad practice to use document.write because it means you MUST run the script before the page finishes loading, and also means you're going to mix your script in with your markup, which will make it harder to maintain in the long run. Better to have clean separation of content/behavior/presentation. However, for this example, I'm assuming this is more of a proof of concept on the math portion, so probably not a big deal.

9. document.write(n+"\t"+"is a composite number")

10. i++

11. document.write(n+"\t"+"is a prime number")

You're prompting the user for a number, n, and then at the end of your script (outside of your while loop) you're always saying that n is a prime number. For example, suppose user enters 4 when prompted... your algorithm will do something like this:

i = 2

while 2 is less than 4,

r = 4 % 2 (r = 0)

if (0 == 0), then you write out:

4 is a composite number

Then you fail to increment i, and you run through the loop again with the same values... [b]you're in an endless loop[/b]!

Even if you were to break out of the loop, you'd end up also writing that the number was prime, since that code is outside of your while loop.

On the other hand, suppose the user entered 5:

i = 2

while 2 is less than 5,

r = 5 % 2 (r = 1)

if (1 == 0), nope, so you go to your else case which increments i:

i++ (i = 3)

Then you go to the top of your loop:

while 3 is less than 5,

r = 5 % 3 (r = 2)

if (2 == 0), nope, so you go to your else case which increments i:

i++ (i = 4)

Then you go to the top of your loop:

while 4 is less than 5,

r = 5 % 4 (r = 1)

if (1 == 0), nope, so you go to your else case which increments i:

i++ (i = 5)

Then you go to the top of your loop:

while 5 is less than 5... nope, so exit the loop, then you write out:

5 is a prime number

So your algorithm works if (and only if) the user enters a prime number.

However, suppose the user enters 1? 1 is not a prime number but your code will do the following:

i = 2

while 2 is less than 1, nope, so exit the loop, then you write out:

1 is a prime number

(which is incorrect)

So first you need to figure out your algorithm. It looks like you're trying to determine if a number is prime or not. A number is prime if it is an integer greater than 1 that has no integral factors but itself and 1. So 2, 3, 5, 7, 11, etc. Lets start with a base case.

If the user enters a number less than 2, it is not prime, and we can stop without going any further. However, your code is just a sequence of instructions that will continue on... we need a way to stop processing when a result is found. A good way to do that is to have a function that we can "return" from.

/**

* Return true if the number passed in is prime, false otherwise

* @param {number} n The number to check whether it is prime

*/

function isPrime(n) {

var i;

if (n < 2) {

// The number was less than 2, therefore is not prime

return false;

}

for (i = 2; i < n; i++) {

if (n % i === 0) {

// The number was divisible, therefore is not prime

return false;

}

}

// if we're still here, the number is prime

return true;

}

This separates out the logic of determining if a number is prime, and writing out the results. Now you can simply do this:

var n;

n = prompt("Enter a natural number");

document.write(n + "\t" + "is a" + (isPrime(n)? " prime": " composite") + " number");

Note, if you're unfamiliar with the (?:) syntax in the line above, you'll get the same result with:

var n;

n = prompt("Enter a natural number");

document.write(n + "\t" + "is a");

if (isPrime(n)) {

document.write(" prime");

}

else {

document.write(" composite");

}

document.write(" number");

This example will work, HOWEVER, it is not the most efficient way to calculate whether a number is prime. Consider this...

Suppose the user wants to know if 7919 is prime. The code above will check EVERY number from 2 to 7919 (7917 iterations through the loop). But once you know that 2 is prime, then every number that's divisible by 2 between 2 and 7919 does not need to be checked. Likewise with 3, every number that's divisible by 3 between 3 and 7919 does not need to be checked. Similarly, any number greater than n / 2 would not need to be checked. For example, if n == 7919, there's no need to check any number greater than 3959 because it's impossible that the number would be divisible by any of those numbers. Or take a simpler case of n = 13. There's no point testing if 7, 8, 9, 10, 11, or 12 go into it.

So there are better algorithms out there for checking primes. The important thing is to have a well defined algorithm.

For comparison purposes, this was my rough-and-dirty version. I didn't allow for non-integers or numbers <2:

`var n,i,r;`

n=prompt("Enter a natural number");

i=2;

var flag = 0;

while (i<=Math.floor(Math.sqrt(n)))

{

r=n%i;

if (r==0)

{

document.write(n + "\tis a composite number");

flag = 1;

i = n; }

else

{ i++ }

}

if (flag == 0)

{ document.write(n + "\tis a prime number"); }

- Register For Free! -
**Become a Pro Member!** - See forum categories - Enter the Forum

- Moderator List | Top Contributors:This Week, This Month, June, May, Archive, Top 100 All Time, Top Voted Members

- Google Updates and SERP Changes - July 2017
- July 2017 AdSense Earnings & Observations
- Authorized Digital Sellers, Ads.txt, Authorized to Sell Their Digital Inventory
- Google Instant Search Results Now Removed
- Google SERP Overriding Title Tag (Unusual)
- It's official: Adobe to kill Flash Player, end support by 2020
- Help! I'm being stalked by a "website groupie"
- Negative SEO Is Alive and Well
- What would you do if Google SERPs just disappeared
- Adsense/AMP

- Authorized Digital Sellers, Ads.txt, Authorized to Sell Their Digital Inventory
- It's official: Adobe to kill Flash Player, end support by 2020
- WordPress: Vulnerability Scanners WPScan, WPSeku
- Google AdSense: No More Pop-Up and Pop Under - New Rule
- GSC July 13-14 Decrease in Average Positions is a Reporting Change... Not a Rankings Drop
- Report: Facebook to Test Subscription News Service
- Google Search App Gets Algorithmic News Feed
- What would you do if Google SERPs just disappeared
- Twitter Adds Advanced Filter Settings With Better Mute Controls
- Most of Your Website Traffic is Not Human