Reputation: 69
I have been trying to get this to work for days now and I still cannot figure out the error. When I output the code, it prints, but it will not find the amicable pairs (divisor of first == second, and vice versa).
#include <stdio.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
int sumDivisors( int num );
int sumDivisors( int num )
{
int counter, total;
for( counter = 1; counter < num; counter++ )
{
if( num % counter == 0 )
{
total += counter;
}
}
return ( total );
}
int main( void )
{
int higher, lower, lowx, lowy, x, y, numOfPairs = 0;
printf( "This program finds all amicable numbers within a range. \n" );
printf( "Please enter a lower limit: \n" );
scanf( "%d", &lower );
printf( "Please enter a higher limit: \n" );
scanf( "%d", &higher );
for( lowx = lower; lowx <= higher; lowx++ )
{
for( lowy = lower; lowy <= higher; lowy++ )
{
if( sumDivisors( lowx ) == sumDivisors( lowy ) )
{
numOfPairs++;
printf( "Pair #%d: (%d, %d)\n", numOfPairs, lowx, lowy );
}
}
}
printf( "There are %d amicable pairs from %d to %d\n", numOfPairs, lower, higher );
system("pause");
return ( 0 );
}
Upvotes: 0
Views: 244
Reputation: 2558
You are not assigning any value to total in your code:
int sumDivisors( int num )
{
int counter, total;
for( counter = 1; counter < num; counter++ )
{
if( num % counter == 0 )
{
total += counter;
}
}
return ( total );
}
so it contains garbage not predictable value!
it should be like: int counter, total = 0;
Upvotes: 6