Форум » C/C++ для начинающих (C/C++ for beginners) » Определить делится ли целое число нацело на квадрат другого целого числа » Ответить
Определить делится ли целое число нацело на квадрат другого целого числа
Сыроежка: Вот очень простое задание (смотрите 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).. [pre2] #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 ); } } } [/pre2] Вывод программы на консоль: [pre2] 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.[/pre2] Обратите внимание, что даже на сайте Stackoverflow, где помещен исходный вопрос, решение задания у многих вызывает трудности.:)
Ответов - 2
Сыроежка: Функцию divisible_by_perfect_square можно переписать также таким образом. что она будет возвращать число, на квадрат которого делится аргумент функции, или 0 в случае, если такое число не найдено. Например, [pre2] #include <stdio.h> unsigned int divisible_by_perfect_square( unsigned int x ) { unsigned int i = 2; while ( i <= x / i && x % ( i * i ) != 0 ) i++; return i <= x / i ? i : 0; } int main(void) { const unsigned int N = 100; for ( unsigned int i = 0; i < N; i++ ) { unsigned int n = divisible_by_perfect_square( i ); if ( n ) { printf( "%2u is divisible by square %2u.\n", i, n * n ); } } } [/pre2] Вывод программы на консоль: [pre2] 4 is divisible by square 4. 8 is divisible by square 4. 9 is divisible by square 9. 12 is divisible by square 4. 16 is divisible by square 4. 18 is divisible by square 9. 20 is divisible by square 4. 24 is divisible by square 4. 25 is divisible by square 25. 27 is divisible by square 9. 28 is divisible by square 4. 32 is divisible by square 4. 36 is divisible by square 4. 40 is divisible by square 4. 44 is divisible by square 4. 45 is divisible by square 9. 48 is divisible by square 4. 49 is divisible by square 49. 50 is divisible by square 25. 52 is divisible by square 4. 54 is divisible by square 9. 56 is divisible by square 4. 60 is divisible by square 4. 63 is divisible by square 9. 64 is divisible by square 4. 68 is divisible by square 4. 72 is divisible by square 4. 75 is divisible by square 25. 76 is divisible by square 4. 80 is divisible by square 4. 81 is divisible by square 9. 84 is divisible by square 4. 88 is divisible by square 4. 90 is divisible by square 9. 92 is divisible by square 4. 96 is divisible by square 4. 98 is divisible by square 49. 99 is divisible by square 9.[/pre2]
Сыроежка: Если есть желание написать соответствующую функцию (например, показанную в первом сообщении этой темы) на языке C++, то она может выглядеть следующим образом, как показано в демонстрационной программе. [pre2] #include <iostream> #include <iomanip> #include <functional> template <typename T> bool divisible_by_perfect_square( T x ) requires std::is_integral_v<T> { T i = 2; while ( i <= x / i && x % ( i * i ) != 0 ) i++; return i <= x / i; } int main() { const unsigned int N = 100; for ( unsigned int i = 0; i < N; i++ ) { if ( divisible_by_perfect_square( i ) ) { std::cout << std::setw( 2 ) << i <<" is divisible by a perfect square.\n"; } } }[/pre2] В этой программе используются конструкция C++ 17 requires. Чтобы код компилировался, например, компилятором gcc HEAD 9.0.0 201809, то следует задать опцию компилятора -fconcepts.
полная версия страницы