my code shows all 100 "lights" with values of 1 and 0, what I need to do (and not managing to..) is to show only the lights which has value of 0 (so it's these lights [and these numbers are what needs to be shown] 1, 4, 9, 16, 25, 36, 49, 64, 81, 100). Thanks for the help.
The current code:
#include <stdio.h>
#include <conio.h>
#define lights 100
int main()
{
int arr[lights] = { 0 }, i, j;
printf("Lights that are off:\n");
for (i = 0; i <= lights; i++)
arr[i] = 1;
for (i = 1; i <= lights; i++)
{
for (j = i; j <= lights; j += i)
{
if (arr[j] == 0)
arr[j] = 1;
else if (arr[j] == 1)
arr[j] = 0;
}
}
for (i = 1; i <= lights; i++)
printf("%d ", arr[i]);
return 0;
_getch;
}
答案 0 :(得分:0)
所以看起来你正试图解决灯泡拼图。 这里有一个很好的解决方案:http://puzzles.nigelcoldwell.co.uk/six.htm
我已修复您的代码以使其正常工作,您必须小心索引。
#define NUM_OF_LIGHTS (100)
void main(void)
{
int bulbs[NUM_OF_LIGHTS] = { 0 };
int i, j;
for (i = 1; i < (NUM_OF_LIGHTS + 1); i++)
{
for (j = i; j < (NUM_OF_LIGHTS + 1); j += i)
{
/* Toggle the indexed bulb.
* Note: adjust the array as it runs from 0 to 99, not 1 to 100.
*/
bulbs[j - 1] ^= 1;
}
}
/* Print out the result. */
printf("Lights that are off:\n");
for (i = 0; i < NUM_OF_LIGHTS; i++)
{
/* Only showing the bulb index for lights that are switched off. */
if (bulbs[i] == 0)
{
printf("%d ", i + 1);
}
}
}