Download Quick Currency Converter

Perfect number/Isperfect C/C++

Description: A Perfect number is one whose sum of divisors(excluding itself) is equal to the number itself. For example, "6" is a perfect number because 1+2+3 = 6 (1,2,3 are divisible by 6). To know more, check out the description of wikipedia for Perfect Number. This program checks if a number is perfect or not.

Difficulty: Easy

Language: C++

Compiler/IDE: Visual Studio, dev C++ (others will work as well)

View Source

#include <iostream>
using namespace std;

bool perfect(int) ;
int main() 
	int num;
	cout<<"Write a number to check whether it is perfect \n";
	cin>> num;
	if (perfect(num)) 
		cout<<"The number is a perfect number\n";
		cout<<"The number isn't a perfect number\n";

bool perfect (int n) 
	int sum=0;
	for (int i = 1; i <= n/2; i++ ) 
		n % i ==0 ? sum+= i  :sum +=0;
	return !(sum - n);

Notes:The project calls a simple function that returns true or false based upon whether the number passsed is perfect or not. The function checks if every number(starting from 2 till its half) is divisible by the given number or not; if it is, its added to the "sum", and if its not , 0 is added. At the end if "sum" equals number passed or equivalently (sum - n ) equals 0, the number is perfect and the function returns true and false otherwise.