Perfect Numbers are those numbers which is equal to the sum of its proper positive divisors (excluding itself). Consider number 6, it has only four proper positive divisors 1, 2, 3 and 6. If we exclude 6, proper divisors left are 1, 2 and 3 and their sum is 6 which is equal to the number itself. So, 6 is a Perfect Number. You can learn more about Perfect Numbers on Wikipedia.
Perfect Numbers have a very good binding with Prime Numbers. Using Euclid’s Method we can find Perfect Numbers using Prime Numbers. Actually Perfect Numbers have following relationship with Prime Numbers.
2p-1 (2p - 1)Here p is a Prime Number and formula calculates corresponding Perfect Number
In this tutorial, I will show you a simple way to find out Nth Perfect Number from Nth Prime Number in C language.
Algorithm:
- Find nth Prime Number using method explained here.
- Using that Prime Number, find out corresponding Perfect Number using the formula explained before.
Instructions:
- Ask the user which Perfect Number he/she wants to find. Check if value enetered is less than 1, then exit the program. If value entered is 1, then Print 1st Perfect Number using 1st Prime Number 2.
int num, p_no, temp, temp2 = 1; printf("Enter which Perfect number you want : "); scanf("%d", &num); if(num < 1) return 0; if(num == 1) { p_no = pow(2, 2 - 1) * (pow(2, 2) - 1); printf("Perfect Number %d is %d", temp2, p_no); } - Now using a
forloop find out nth Prime Number and then find out nth Perfect Number as shown below.
for(temp = 3; temp2 < num; temp += 2) { if(isPrime(temp)) { temp2++; if(temp2 == num) { p_no = pow(2, temp - 1) * (pow(2, temp) - 1); printf("Perfect Number %d is %d", temp2, p_no); } } } - Here is
isPrimefunction to check whether a number is Prime or not.
int isPrime(int num) { int i = 2; while(i <= sqrt(num)) { if(num % i == 0) return 0; else i++; } return 1; }
Following images are screenshots of the working code.
You can also download the sample working code from here.
Incoming search terms:
- 16f887a tutorials (3)
- insql wonderware sql problem (3)
- how to create hotmail like textbox rss c# (3)
- CheckedListBox1 selectedvalue tag vb net (2)
- cs full control (2)
- to-change ru (2)
- how to make gcd in windows form (2)
- sorting gridview in C# using anchor tag (2)
- sky response 503 service unavailable (2)
- select all checkbox in checklistbox vb net howtoideas com (2)

