Reputation: 597
So the idea behind my code is to create a program that uses functions to check and print all perfect numbers between 1 and 1000. I've come up with this, but the issue is that nothing prints. It builds successfully, runs, and exits.
I've gone through my code 3-4 times and I can't find the gap in logic, so I'm thinking its a variable definition issue, something to do with how in-scope certain functions are. Would anyone have any input for why my program is failing to recognize a perfect number, and then print it?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
*
*/
void perfectNumCheck(int num);
void perfectNumPrint (int perfectNum);
int main(void) {
int i;
for (i = 1; 1 <= 1000; i++)
perfectNumCheck(i);
}
void perfectNumCheck(int num) {
int i;
int temp = 0;
for (i = 0; i < num; i++) {
if (num % i == 0)
temp += i;
}
if (temp == num)
perfectNumPrint(num);
}
void perfectNumPrint(int perfectNum) {
int i;
for (i = 0; i < perfectNum; i++)
if (perfectNum % i == 0)
printf ("%d, ", i);
printf("are factors of the perfect number %d.\n", perfectNum);
}
Upvotes: 1
Views: 860
Reputation: 21
boolean perfectNum(int currentNum) {
int i, sum = 0;
for (i = 1; i < currentNum; i++)
if (perfectNum % i == 0)
sum += i;
if(sum == currentNum) return ture;
return false;
}
Upvotes: 1
Reputation:
Try this:
boolean perfectNum(int currentNum) {
int i, sum = 0;
for (i = 1; i < currentNum; i++)
if (perfectNum % i == 0)
sum += i;
if(sum == currentNum) return ture;
return false;
}
Upvotes: 0
Reputation: 1
Perfect Number Test : If the sum of all factors are equals to number itself.
public static bool IsItPerfectNumber(int input)
{
bool IsPerfectNumber = false;
//Validation and Find all Factore
List<int> myList = FindFactors(input);
//Sum if factor
int sumOfFactor = SumFactor(myList);
//Check Is Perfact Number
if (sumOfFactor == input)
{
IsPerfectNumber = true;
}
return IsPerfectNumber;
}
public static List<int> FindFactors(int input)
{
List<int> myList = new List<int>();
for (int j = 1; j < input; j++)
{
if (input % j == 0) {
myList.Add(j);
}
}
return myList;
}
public static int SumFactor(List<int> myList)
{
return myList.Sum();
}
Upvotes: 0
Reputation: 1926
You have a typo here:
for (i = 1; 1 <= 1000; i++)
perfectNumCheck(i);
Should be
for (i = 1; i <= 1000; i++)
perfectNumCheck(i);
Also, you're dividing by zero. Change all your i = 0
in your for loops to i = 1
Upvotes: 2