1 Replies - 12711 Views - Last Post: 17 September 2008 - 05:50 PM Rate Topic: -----

#1 Tarquin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 17-September 08

Perfect numbers between 1 to n

Post icon  Posted 17 September 2008 - 10:35 AM

what i cannot get is--
To Print All Perfect Numbers upto Given Number.....i think we have to use for loop and while loop.....plz help!
I know the code to check if given number is perfect or not.....
/*
	WAP to find number is Perfect Number or not
*/

#include<stdio.h>
#include<conio.h>


void main()
{
	int i,no,sum=0;

	clrscr();

	printf("Enter no : ");
	scanf("%d",&no);

	for (i=1; i<no; i++)
	{
		if (no%i==0)
			sum=sum+i;
	}

	if (no==sum)
		printf("\n %d is a Perfect Number",no);
	else
		printf("\n %d is not a Perfect Number",no);

	getch();
}



i need the code to Print all the perfect numbers between 1 to n...plz help

Is This A Good Question/Topic? 0
  • +

Replies To: Perfect numbers between 1 to n

#2 thenovices  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 74
  • Joined: 19-January 08

Re: Perfect numbers between 1 to n

Posted 17 September 2008 - 05:50 PM

its pretty simple. you have whats called "nested loops", where you have loops within loops. Basically you loop through every number from 1 to whatever number was input and check if its a perfect number.

Here's my code: (Sorry its in C++, I already finished writing it before I realized you were coding in C. Hopefully you can still understand it)
#include<iostream>
using namespace std;

int main() {
	int num;
	int sum = 0;
	
	cout << "Find all the perfect numbers up to number: ";
	cin >> num;
	
	for (int i = 1; i <= num; i++) { //check every number from 1 to num
		for (int j = 1; j < i; j++) { //check every number from 1 to i-1 for divisibility
			if (i % j == 0) // if j divides evenly into i
				sum += j; //add j (the divisor) to the sum
		}
		if (sum == i) //if the sum of the divisors equals the number
			cout << i << endl; //print out the perfect number
		
		sum = 0; //reset the sum
	}
	
	cout << "DONE!" << endl;
	
	return EXIT_SUCCESS;
}


This post has been edited by thenovices: 17 September 2008 - 05:50 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1