C++/Factors

Advertisement


Question
Could u please help me solve the foll. question in C++:

Write a program to enter any positive integer & print whether it is a perfect number or not.
(If a number is equal to sum of all its factors it is said to be a perfect number ex.6=1+2+3)
Thanks.


Answer
Dear Pl,
Thankyou for your question.
Well its quiet an interesting problem, well let me
tell your first there are only 4 perfect numbers from
1 to 1000, may be ahead of it also.

Your problem says to find the perfect number.
You should attack this problem like

a) Find the factors of that number. More appropriately
make a function say perfect, which takes an integer
argument.

b)Secondly i already told you have to find the factors.
According to maths, a number can a factor of other number
if it is its half.
Umm, example, lets your number is 6, so it can take factors
upto 3, because 3 is 6's half. Plus always remeber 1 is the factor of all numbers so you can write a simple code in your function like

int product = 1 ;
for( int i = 1 ; i <= ( n / 2 ) ; i++ )
// 'n' is the positive number you entered.

//Simply put a check like this now
if( n % i == 0 )
 product += i ;
 return true ;// the number is perfect.

That is simple like this, i hope i have tried to explain clear. If you have any more queries, dont be afraid to ask.
Hope this helps.

Regards
Professional

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Professional

Expertise

I can answer any question about functions,pointers,structures,object oriented programming basics of classes and data structures.My strong field is structured programming.

Experience

I have got 2 years experiece under C . I am able to answer about the structured concepts pointers to a little extent,OOP concepts. I have also experience in data Strucutres like Linked List, Stacks , Queues, Heaps, B Trees, Red Black Trees. I will try to satisfy with my knowledge. I am the Student of an expert here Martin, what i have learnt today, i just owe my every knowledge to him. He is the greatest.

©2016 About.com. All rights reserved.