Hey,
So I'm trying to learn C on my own, and I've just started through a book and am having a problem with an exercise.
Problem: There are 500 light bulbs (numbered 1 to 500) arranged in a row. Initially they are all OFF.
Starting with bulb 2, all even numbered bulbs are turned ON. Next, starting with bulb 3, and visiting every 3rd bulb, it is turned ON if it is OFF, and it is turned OFF if it is ON.
This procedure is repeated for every fourth bulb, then every fifth bulb, and so on up to the 500th bulb. Write a program to determine which bulbs are OFF at the end of the exercise.
The result I'm getting with the code below is that only the first bulb is OFF at the end, which I don't believe can possibly be correct becuase the prime numbered bulbs should never be changed from OFF.
Any help on where I made a mistake?
Thanks
Code:
#include <stdio.h>
int main()
{
int numbulbs = 501, i = 0, j = 0, k = 0;
int bulbs[numbulbs];
for(i = 0; i <= numbulbs; i++)
{
bulbs[i] = 0; // all bulbs set to OFF
}
for (j = 2; j <= numbulbs; j++)
{
for (k = j; k<=numbulbs; k++)
{
if( ( k%j ) == 0)
{
if(bulbs[k] == 1)
bulbs[k] = 0;
if(bulbs[k] == 0)
bulbs[k] = 1;
}
}
}
for( j = 1; j <= numbulbs; j++)
{
if (bulbs[j] == 0)
printf("Bulb number %i is OFF\n", j);
}
return 0;
}