-
need correction
Hi can anybody correct my code please?
Code:
/*Write an algorithm that gets a positive entire number N then displays all perfect numbers less or
equal to N.*/
#include<stdio.h>
int main (void){
int i,n,sum_div,num;
char ans;
do{
sum_div=0;
printf("---------------\n");
printf("Enter number:");
scanf("%d", &n);
printf("Perfect numbers in the range [1,%d]:", n);
for(num=2;num<=n;num++){
for(i=1;i<=num/2;i++){
if(num%i==0)
sum_div+=i;
}
if(sum_div==num)
printf("%d ",num);
}
printf("\nContinue? <Y/N>:");
scanf(" %c", &ans);}
while(ans=='Y'||ans=='y');
printf("Bye:>_n\n");
return(0);
}
-
sum_div needs to be initialized to 0 each time before you start adding to it.
-
i think the pblm is with the for loops. but how do i initialize that each time?
-
Code:
for(num=2;num<=n;num++){
sum_div = 0;
for(i=1;i<=num/2;i++){
if(num%i==0)
sum_div+=i;
-
ohh thank youuuuuuuuuuu (k)
-
To be even more direct about the rareness of perfect numbers how about writing a function like this.
Example:
Code:
#include <stdio.h>
#include <ctype.h>
Include those two so that you can have your printf() and scanf() functions. You also need toupper() from ctype.h
Code:
const static long unsigned long perfect_numbers[] = {6, 28, 496, 8128, 33550336, 8589869056, 137438691328};
"But Matt, that doesn't seem like so many numbers!!! You are ruining my program."
That list constitutes all of the perfect numbers your computer will be able to safely comprehend without using GMP or something.
Code:
int is_perfect(long unsigned long value)
{
size_t i;
for(i = 0; i < sizeof(perfect_numbers)/sizeof(*perfect_numbers); ++i)
if(value == perfect_numbers[i])
return 1;
return 0;
}
All this function does is compares an input value (as a 64-bit value) to the list of known perfect numbers.
Code:
int main(void)
{
unsigned int n, i = 0;
while(toupper(i) != 'N')
{
do
{
fputs("> Please input a number: ", stdout);
} while(scanf("%d", &n) != 1);
for(i = 0; i < n; ++i)
if(is_perfect(i))
printf("** %d is perfect!! **\n", i);
fputs("> Continue? ", stdout);
i = getchar();
}
}
Make sense?
-
thank you master5001 it works now, tabstop found out i just had to initialize sum_div correctly. thanks yall.
-
I know. I just think you should be aware of the fact that its slow to check every number to see if its perfect or not when there are soooooooooooooooooooooooooooo many numbers that are not perfect. We only know of 44 of them now. And with the aid of google I found a list of them.
I changed the code to get rid of that warning for you :)