I have to write a code determining if a number is a prime number or not, a perfe
ID: 3625032 • Letter: I
Question
I have to write a code determining if a number is a prime number or not, a perfect number or not. Output a list of all divisors of numbers that are not prime and a list of divisors of all perfect numbers. FOrmat output so there is between 5 and 10 numbers per line to conserve paper. The input should be limited to numbers from 1 to 1000. Check your solution with at least 6 numbers: at least 2 prime numbers; at least 2 perfect numbers; at least 2 numbers that are neither prime nor perfect.In case you don't know what a prime or perfect number is:
Prime Number: is one whose only exact divisors are 1 and the number itself(such as 2, 3,5,7,etc).
Perfect Number: a number whose exact divisors (except the number itself) sum to equal the number. For example, 6 has 3 divisors 1,2,3 which add up to 6. Therefore 6 is a perfect number.
Bascially, I have to write a program that consists of loops, I understand the structure,I'm having difficulty with the algorithm as in how to make the program test prime and perfect numbers. Any help would be helpful. Thanks
Note: As for the perfect numbers, I get the idea of probably using square root, but I dont know how to apply it as code. If anyone knows any other ways or have any suggestions in writing this program out, that would be helpful
Explanation / Answer
#include<iostream>
using namespace std;
bool isprime(int n)
{
for (int i=2; i < n ;i++ )
{
int num = n%i;
if (num==0)
{
return false;
break;
}
}
return true;
}
bool isperfect(int n)
{
int sum=0;
for(int i=1; i<n; i++)
if(n%i == 0)
sum = sum + i;
if(sum == n) return true;
else return false;
}
int main()
{
// int n;
// cout << "enter number";
// cin >> n;
for(int n=2; n<13000; n++)
if(isprime(n) && isperfect(n))
cout << n << " is both prime and perfect" <<endl;
// else cout << "Given is not a prime and perfect " <<endl;
system("pause");
return 0;
}