C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Sunday, December 15, 2013

Program To Check Input for Perfect Number

Write a C++ program to check whether a given input number is a perfect number or not.

Solution:

What is a Perfect Number?


In number theory, a perfect number may be defined as a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.

So we will find all positive divisors(excluding the number itself) of the given number and get sum of these. If the sum is equal to the given number then IT IS A PERFECT NUMBER, otherwise not. For example, 6 is a perfect number. Because, sum of proper divisors of 6 is:
1+2+3 = 6.


perfect number C++ program

Here is the C++ Program Code for PERFECT NUMBER CHECK!


/*
Write a C++ Program to input a positive number, then check
whether this number is a perfect number?

For Free C++ Programming Techniques (Example Programs), visit
Www.EasyCppProgramming.Blogspot.Com

and For Good Notes
Visit   Www.ForFreeEducation.Blogspot.Com
*/
#include<iostream.h>

#include<conio.h>

void main()
{

  clrscr();

  long number, sum=0, counter, mid, count=0;

  cout<<"\n Enter the positive number\nto check for Perfect Number= ";

  cin>>number;

  mid = number / 2;

  cout<<"\n\n ----------- Results ------------";

  cout<<"\n\n Proper Positive Divisors of \n that is divisors excluding \nthe number itself "<<number<<" are=";

  for (counter = 1; counter <= mid; counter++)
           {
           cout<<"\n \t"<<counter;
           sum = sum + counter;
           }
           cout<<"\n Sum of Proper divisors ="<<sum;
 if ( number == sum )
 cout<<"\n The number is Perfect Number";
 else
 cout<<"\n the number is not a Perfect Number";


  getch();

}
Share:

0 comments:

Post a Comment

We Love To Hear From You!

EasyCPPprogramming.blogspotcom

Blog Archive

Labels