Aliquot
I'm trying to make a recursive function, but I need help, as I keep getting into a nullpointer error
2 Replies
c#
public class Program
{
public static int[] GenerateDivisors(int n)
{
if (n <= 0)
{
return null;
}
List<int> divisors = new List<int>();
for (int i = 1; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
divisors.Add(i);
if (i != n / i)
{
divisors.Add(n / i);
}
}
}
divisors.Sort();
divisors.Remove(n);
return divisors.ToArray();
}
public static int GetSumOfDivisors(int[] x)
{
int total = 0;
for (int i = 0; i < x.Length; i++)
{
total += x[i];
}
return total;
}
private static void GetNextNumber(int x)
{
var values = GenerateDivisors(x);
var sum = GetSumOfDivisors(values);
while (true)
{
Console.WriteLine(x);
if (x == 0)
{
return;
}
GetNextNumber(sum);
}
}
public static void Main(string[] args)
{
GetNextNumber(18);
}
}
c#
public class Program
{
public static int[] GenerateDivisors(int n)
{
if (n <= 0)
{
return null;
}
List<int> divisors = new List<int>();
for (int i = 1; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
divisors.Add(i);
if (i != n / i)
{
divisors.Add(n / i);
}
}
}
divisors.Sort();
divisors.Remove(n);
return divisors.ToArray();
}
public static int GetSumOfDivisors(int[] x)
{
int total = 0;
for (int i = 0; i < x.Length; i++)
{
total += x[i];
}
return total;
}
private static void GetNextNumber(int x)
{
var values = GenerateDivisors(x);
var sum = GetSumOfDivisors(values);
while (true)
{
Console.WriteLine(x);
if (x == 0)
{
return;
}
GetNextNumber(sum);
}
}
public static void Main(string[] args)
{
GetNextNumber(18);
}
}
i see that
GenerateDivisors
can return null
and you're not checking for that in GetSumOfDivisors
also, what is line 127?