LP Assignments 1 Sol
LP Assignments 1 Sol
Assignment 1
To test if a number x is a prime, we'll have to test every integer number greater than 1 and smaller than x,
to check if it is a divisor of x. If at least one is a divisor, then x is not a prime. If none is a divisor, then x is
a prime.
Improvement: test only 2 and then only the odd numbers. Why?
Improvement: test only possible divisors smaller than the square root of x. Why?
namespace Primos {
class Program
{
static Boolean PrimeTest(int i)
{
if (i < 2)
return false;
if (i == 2)
return true;
if (i % 2 == 0)
{ // tests for even
return false;
}
for (int c = 3; c < Math.Sqrt(i); c += 2)
{ // tests only odd numbers
if (i % c == 0)
{
return false;
}
}
return true;
}
static void Main(string[] args)
{
Console.WriteLine("7: {0}", PrimeTest(7));
Console.WriteLine("787: {0}", PrimeTest(787));
Console.WriteLine("2: {0}", PrimeTest(2));
Console.WriteLine("37: {0}", PrimeTest(37));
Console.WriteLine("25: {0}", PrimeTest(25));
Console.WriteLine("73: {0}", PrimeTest(73));
Console.WriteLine("74: {0}", PrimeTest(74));
Console.WriteLine("75: {0}", PrimeTest(75));
Console.WriteLine("79: {0}", PrimeTest(79));
Console.ReadKey();
}
}
}
A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the
sum of its positive divisors excluding the number itself. Example: 28 = 1 + 2 + 4 + 7 + 14
Page 1 / 3
Programming Laboratories
Assignment 1
2) Write a program that finds and prints all the perfect numbers smaller than a given value
class Program
{
static Boolean Perfect(int i)
{
if (i < 3)
return false;
int sum = 1;
for (int c = 2; c <= i / 2; c++)
{
if (i % c == 0) // c is a divisor of i?
{
sum += c; // add c to the sum of divisors
}
}
return sum == i; // sum == i ?
}
static void PrintPerfect(int max)
{
for (int m = 2; m < max; m++)
{
if (Perfect(m))
{
Console.WriteLine("{0} is perfect", m);
}
}
}
Find the square root of a given number a (greater than zero), using an iterative method.
The algorithm is to repeat a simple calculation that results in a number closer to the actual square root
each time it is repeated with its result as the new input.
newx = (x + a / x) / 2
x e a/x define an interval that contains the square root of a. If x is smaller than the root, then a/x is larger,
and vice-versa. newx is the middle point of that interval. Each new value of x is closer to the root. We
repeat the calculation until the interval is smaller than the required error for the root value.
class Program
{
private static double Root(double a, double error)
{
Page 2 / 3
Programming Laboratories
Assignment 1
double x = 1;
double newx = (x + a / x) / 2;
while (Math.Abs(x - a / x) > error)
{
x = newx;
newx = (x + a / x) / 2;
// Console.WriteLine("x= {0:0.0#####} a/x= {1:0.0#####} newx=
{2:0.0#####}", x, a / x, newx);
}
return x;
}
Page 3 / 3