C/C++
Задача по C++(сделать через void)
Вводится последовательность целых чисел, 0 - конец последовательности. Найти количество совершенных чисел в последовательности (функцией оформить проверку числа: результатами функции будет 1-число совершенное, 0-нет.)
#include <iostream>
#include <vector>
using namespace std;
using perfect_t = unsigned;
bool perfect_number(perfect_t num) {
if (num & 1) return false;
auto m = num >> 1;
auto sum = 0ULL;
for (decltype(num) x = 1; x <= m; ++x) {
if (0 == num % x) sum += x;
if (sum > num) return false;
}
return sum == num;
}
size_t count(const vector<perfect_t>& box) {
auto n = 0U;
for (auto x : box) if (perfect_number(x)) ++n;
return n;
}
int main() {
vector<perfect_t> box;
unsigned value;
while (true) {
cin >> value;
if (!value) break;
box.push_back(value);
}
auto x = count(box);
cout << x << endl;
system("pause > nul");
}
#include <vector>
using namespace std;
using perfect_t = unsigned;
bool perfect_number(perfect_t num) {
if (num & 1) return false;
auto m = num >> 1;
auto sum = 0ULL;
for (decltype(num) x = 1; x <= m; ++x) {
if (0 == num % x) sum += x;
if (sum > num) return false;
}
return sum == num;
}
size_t count(const vector<perfect_t>& box) {
auto n = 0U;
for (auto x : box) if (perfect_number(x)) ++n;
return n;
}
int main() {
vector<perfect_t> box;
unsigned value;
while (true) {
cin >> value;
if (!value) break;
box.push_back(value);
}
auto x = count(box);
cout << x << endl;
system("pause > nul");
}
В гугле заблокировали? И что значит "Сделать через void" если ты хочешь получить результат с количеством простых элементов из функции?
Ну пример вот:
// проверка числа на совершенность
bool isPerfect(int num)
{
int sum = 0;
for (int j = 1; j <= num / 2; j++)
{
if (num % j == 0)
sum += j;
}
return sum == num;
}
int nPerfectNumbers (const std::vector numbers)
{
int counter = 0;
for(int num : numbers)
if(isPrefect(num))
++counter;
return counter;
}
Если нужен void, то в функцию надо передать по ссылке переменную counter типа так:
void nPerfectNumbers(const std::vector numbers, int& counter)
{
counter = 0// обнуляем счетчик, если он вдруг не нулевой
...
}
Ну пример вот:
// проверка числа на совершенность
bool isPerfect(int num)
{
int sum = 0;
for (int j = 1; j <= num / 2; j++)
{
if (num % j == 0)
sum += j;
}
return sum == num;
}
int nPerfectNumbers (const std::vector numbers)
{
int counter = 0;
for(int num : numbers)
if(isPrefect(num))
++counter;
return counter;
}
Если нужен void, то в функцию надо передать по ссылке переменную counter типа так:
void nPerfectNumbers(const std::vector numbers, int& counter)
{
counter = 0// обнуляем счетчик, если он вдруг не нулевой
...
}
Eziz Abdyraimow
Не получается почему-то исправления внести. Поторопился. std::vector передаем в функцию, думаю, понятно)