Displaying Prime Numbers Using document.write() - javascript

I have an assignment for school that I seem to be stuck on.
Write a script that prints the prime numbers between 1 and 999 in a table that consists >of 10 columns. Use document.write() statements to create the table elements and a >counter variable to create the table so that it consists of 10 columns. The counter >variable should start with an initial value of 0 and be incremented by one each time your >code identifies a prime number and prints it in a table cell. Once the counter variable >reaches a value of 10 (meaning that 10 cells have been added to the current row), print >to start a new row and reset the variable to 0.
I cannot figure out where my error or errors are with the table row and counter. Also, I might have placed the document.write() methods in the wrong places. Currently, the table only displays vertically.
Here is what I have:
<script>
function primeNumbers(num) {
document.write('<table>');
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
Please, push me in the right direction and don't give me the answer. I want to see if I can figure this out.
Thanks!

There were some errors in your code:
The <table> opener was inside the function, so actually it was opening 1000 times.
The counter is reset, so you don't need to use modulus (%), just compare to 10.
A </tr> was missing in the end
Your function primeNumbers is misnamed, the best would be call isPrime
Here's the code:
function isPrime(num) {
if (num < 2) return false;
for (var i = 2; i < num; i++) {
if (num % i == 0) return false;
}
return true;
}
document.write("<table><tr>");
var counter = 0;
for (var i = 0; i < 999; i++) {
if (isPrime(i)) {
if (counter == 10) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</tr></table>');
Here's the fiddle working (I can't use document.write here, but you get the idea) http://jsfiddle.net/bortao/D2bzk/

Try this: http://jsfiddle.net/ezn7f/
<script>
function primeNumbers(num) {
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<table><tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
I wonder if this is what you are looking for though. I didn't change much in your code.

Related

Why is this code looping infinitely?

I'm trying to write a program in JavaScript that generates 100 random numbers and checks the primality of each. The program does just that, except for some reason it doesn't stop at 100 and just loops infinitely. I'm sure I made some simple novice mistake, but for some reason I can't see it. Any advice?
My code:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}
Thanks!
You need to declare i variable in for-loops:
(var i = 0; i < 100; i++) ...
otherwise it is defined in global scope and it is shared between for-loop and isPrime function.
madox2 is correct that you should declare i in the for loop, however I think the reason the loop itself is infinite is because by only doing i=0 in the loop, and then for (i = 2; i <= r; i++) in the function the loop calls, you are resetting i every iteration
You should change your code to declare i within the scope of both loops separately, like so:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (var i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (var i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}

Function called but without reference to parameter

I wrote the following code and something strange happens. The last line fizzbuzz(15) where I call the function is necessary to get the loop to run, but does not take into account the parameter, in this case, 15. How can I integrate the parameter into my function?
function fizzbuzz(num) {
for(num = 0; num < 20; num++) {
if(num % 3 === 0 && num % 5 === 0){
result = "fizzbuzz";
}
else if(num % 3 === 0){
result = "fizz";
}
else if(num % 5 === 0){
result = "buzz";
}
else if(num % 3 !==0 && num % 5 !==0){
result = num;
}
console.log(result);
}
}
fizzbuzz(15);
for(num = 0; num < 20; num++) {
You're changing it back to 0 here every time you run this. It doesn't matter what you pass in if you keep assigning zero.
I suppose this is what you're after:
for(num; num < 20; num++) {
Or, if you are after setting the number of iterations, then this:
for(var i = 0; i < num; i++) {
(and then change all of your references inside of the loop from num to the more idiomatic i)

for/while loop for reading user input

I'm kinda new to programming and I got this question in a quiz. I need to write a JavaScript program to read 10 positive values from the user, and then sum only the multiples of 3 and 5.
I couldn't even finish the code. help?
var x = new Array ();
var total;
x.push(parseFloat(window.prompt("enter a value",""),));
for (x.length<=10; i=0; i<10; i++) {
total += x[i]
}
else{
document.write(total);
}
You need to put your prompt function inside for loop and add check if number is multiply by 3 or 5.
var total;
for (var i=0; i<10; i++) {
var num = parseFloat(window.prompt("enter a value",""));
if (num % 3 == 0 || num % 5 == 0) {
total += num;
}
}
document.write(total);
UPDATE:
var total;
var i = 0;
while (i<10) {
var num = parseFloat(window.prompt("enter a value",""));
if (num >= 0 && (num % 3 == 0 || num % 5 == 0)) {
total += num;
i++;
}
}
document.write(total);
thanks, i did set total=0 so that after the sum it prints out a value instead of NaN
var total = 0;
var i = 0;
while (i < 10) {
var num = parseFloat(window.prompt("enter a value", ""));
if (num >= 0 && (num % 3 == 0 || num % 5 == 0)) {
total += num;
i++;
}
}
document.write(total);

Counting occurances of character in strings

I made a function that counts the occurances of x's and o's in a given string and returns true if they are equal.
function ExOh(str) {
var x_count = 0;
var o_count = 0;
for (var i = 0;i < str.length-1;i++){
if (str[i] === 'x'){
x_count = x_count + 1;
}
else if (str[i] === 'o'){
o_count = o_count + 1;
}
}
console.log(o_count);
console.log(x_count);
if (x_count === o_count){
return true;}
else{
return false;
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
ExOh(readline());
I added the lines of code
console.log(o_count);
console.log(x_count);
To see if it was counting correctly and I discovered that was the issue. After testing it I realized that this function is not testing the last element in the string. I tried changing the length of the for loop, but I can't think of what else could be wrong.
Any advice?
Thanks mates
JavaScript arrays are 0 index based objects. So, your loop should be like this
for (var i = 0; i < str.length; i++) {
otherwise the last element will be skipped.
Consider that the length of the string is 5. So, i starts from 0 and if you had your original condition
for (var i = 0; i < str.length - 1; i++) {
following are the comparisons happening in the loop
0 < 4
1 < 4
2 < 4
3 < 4
4 < 4 -- Fails
So it breaks out of the loop. But the last element will be at index 4. But when you have the condition like this
for (var i = 0; i < str.length; i++) {
the comparisons go like this
0 < 5
1 < 5
2 < 5
3 < 5
4 < 5
5 < 5 -- Fails
It breaks out of the loop only after comparing all the elements.
So, your actual program can be written like this
function ExOh(str) {
var x_count = 0, o_count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === 'x') {
x_count = x_count + 1;
} else if (str[i] === 'o') {
o_count = o_count + 1;
}
}
return x_count === o_count;
}
alternate method to count characters:
var s = 'example';
s.split('').filter(function (i) { return i === 'e'; }).length; // 2
Your for loop is running one too short. Try this instead.
for (var i = 0;i < str.length;i++){
if (str[i] === 'x'){
x_count = x_count + 1;
}
else if (str[i] === 'o'){
o_count = o_count + 1;
}
}
Your problem is in for loop. Try changing to this.
for (var i = 0; i < str.length; i++) {
If you want to avoid using for loops, you can use this much shorter version of ExOh function.
function ExOh(str) {
return str.match(/o/g).length == str.match(/x/g).length
}
Rather than looping over the whole String with for, I'd see if using indexOf achieves a faster result
function countOccurance(haystack, needle) {
var total = 0, pos = -1;
while (-1 !== (pos = haystack.indexOf(needle, pos + 1)))
total += 1;
return total;
}
Then
var x_count = countOccurance(str, 'x'),
o_count = countOccurance(str, 'o');
return x_count === o_count;
EDIT looks like I might have been wrong about it being faster! jsperf
function indexOfMethod(haystack, needle) {
var total = 0, pos = -1;
while (-1 !== (pos = haystack.indexOf(needle, pos + 1)))
total += 1;
return total;
}
function splitMethod(haystack, needle) {
return haystack.split(needle).length - 1;
}
function forMethod(haystack, needle) {
var total = 0, i;
for (i = 0; i < haystack.length; ++i)
if (haystack.charAt(i) === needle)
total += 1;
return total;
}
The forMethod will only work with char needle, whereas the other two should work with any String as needle, if that matters.

sorting an alphanum array using jQuery

i am trying to compare two arrays containing alphabets and numbers using jquery but a call to the function does nothing.
jQuery.compare = function (string2,string1) {
alert("comparing")
var i, j;
for ( i = 0, j=0; i < string2.length|| j<string1.length; ++i,++j) {
var n1 = 0,n2=0;
if ($.isNumeric(string2[i+1])) {
num=string2[i]
while ($.isNumeric(string2[i+1])) {
i++;
num += string2[i]
}
n1 = 1;
}
if ($.isNumeric(strin1[j])) {
num1 = string1[j]
while ($.isNumeric(string1[j+1])) {
j++;
num1 += string1[j]
}
n2 = 1;
}
if (n1 == 1) {
if (n2 = 1) {
if( parseInt(num1) - parseInt(num) !=0)
return parseInt(num1) - parseInt(num);
}
else
return 1;
}
else if (n2 = 1)
return -1;
else {
if(string2[i]-string1[j]!=0)
return string2[i]-string1[j]!=0;
}
}
if (j < string1.length)
return -1;
else
return 1;
}
Also i would like to know the best way to call this function. I would like to use something like string1.compare(string2) and replace string1 with 'this' in the above code fragment.
EDIT:
This is how i call the compare function.Here, colValues is an array of string.
$.fn.sort = function (colValues) {
alert("sorting")
var i;
for (i = 0; i < colValues.length; ++i) {
for (var j = 0; j < i - 1; ++j) {
alert("before compare")
if(colValues.compare(colValues[j],colValues[j + 1])) {
var temp = colValues[j];
colValues[j] = colValues[j + 1];
colValues[j + 1] = temp;
}
}
}
return colValues
}
if i replace
if(colValues.compare(colValues[j],colValues[j + 1]))
with
if(colValues[j]>colValues[j+1])
my sort function works.
i am a complete newbie at coding in jquery. There is probably some syntactical error. I dont really want any help with the algorithm just the syntax.
jsfiddle-checkout my code here
EDIT2:
i fixed everything thx to metadings.
heres what i had to change
1)
jQuery.compare
to
$.fn.compare
2)
if($.isNumeric(string2[i+1]))
to
if(jQuery.isNumeric(string2[i + 1]))
somehow the
while ($.isNumeric(string1[j+1]))
syntax worked without any changes
3)
parseInt(num1) - parseInt(num)
didnt work either as it returned NaN. To solve this problem i defined two var variables 'number1' and 'number2' and initialized them with 0's and assigned parseInt(num1) individually to the variables and then subtracted the new variables.

Categories

Resources