Вот очень простое задание (смотрите
Problem with my code to find if a number is divisible by a perfect square), но требующее аккуратности при написании кода.
Задание, как следует из вопроса, представленного по ссылке, состоит в том, чтобы для заданного целого числа
x определить делится ли оно нацело на квадрат другого числа
i из диапазона
[2, i * i <= x]..
Для этой задачи важно, чтобы в цикле не было бы переполнения целых чисел, иначе программа будет иметь неопределенное поведение.
Вот как может выглядеть соответствующая функция, которая определяет заданное условие, как показано в нижеприведенной демонстрационной программе, для чисел из диапазона
[0, N), где
N - некоторое произвольное число (в демонстрационной программе установленное равным
100)..
#include <stdio.h>
_Bool divisible_by_perfect_square( unsigned int x )
{
unsigned int i = 2;
while ( i <= x / i && x % ( i * i ) != 0 ) i++;
return i <= x / i;
}
int main( void )
{
const unsigned int N = 100;
for ( unsigned int i = 0; i < N; i++ )
{
if ( divisible_by_perfect_square( i ) )
{
printf( "%2u is divisible by a perfect square.\n", i );
}
}
}
Вывод программы на консоль:
4 is divisible by a perfect square.
8 is divisible by a perfect square.
9 is divisible by a perfect square.
12 is divisible by a perfect square.
16 is divisible by a perfect square.
18 is divisible by a perfect square.
20 is divisible by a perfect square.
24 is divisible by a perfect square.
25 is divisible by a perfect square.
27 is divisible by a perfect square.
28 is divisible by a perfect square.
32 is divisible by a perfect square.
36 is divisible by a perfect square.
40 is divisible by a perfect square.
44 is divisible by a perfect square.
45 is divisible by a perfect square.
48 is divisible by a perfect square.
49 is divisible by a perfect square.
50 is divisible by a perfect square.
52 is divisible by a perfect square.
54 is divisible by a perfect square.
56 is divisible by a perfect square.
60 is divisible by a perfect square.
63 is divisible by a perfect square.
64 is divisible by a perfect square.
68 is divisible by a perfect square.
72 is divisible by a perfect square.
75 is divisible by a perfect square.
76 is divisible by a perfect square.
80 is divisible by a perfect square.
81 is divisible by a perfect square.
84 is divisible by a perfect square.
88 is divisible by a perfect square.
90 is divisible by a perfect square.
92 is divisible by a perfect square.
96 is divisible by a perfect square.
98 is divisible by a perfect square.
99 is divisible by a perfect square.
Обратите внимание, что даже на сайте
Stackoverflow, где помещен исходный вопрос, решение задания у многих вызывает трудности.:)