Tuesday, December 2, 2014

Faster but probabilistic way & C++ roots using Newton's method



Compute square roots using Newton's method
 
#include 
#include
#include 
float asqrt (float x, float precision) 
{
  float guess;
  guess = 1.0;
  while (fabs(guess*guess-x) >= precision) 
  {
    guess = 0.5 * (guess + (x / guess));
  }
  return (guess);
}
int main () 
{
  float x, precision; 
  cout << "Enter a real number and the precision: ";
  cin >> x >> precision;
  cout << "sqrt(" << x << ") is almost " << asqrt(x,precision) << endl;
  return(0);
}
 
Compute distance between cities
 
#include
#include 
#include
float toRadian (float angle) 
{
float const PI = atan(1.0)*4.0;
  return(angle * PI / 180.0);
}
float computeDist (float lat1, float long1, float lat2, float long2) 
{
  float const R = 3964.0;
  float temp;
  temp = sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(long1-long2);
  return(2.0 * R * atan(sqrt((1.0-temp)/(1.0+temp))));
}
void main () 
{
  float lat1, long1, lat2, long2, distance;
  cout << "Enter lat1, long1: ";
  cin >> lat1 >> long1;
  cout << "Enter lat2, long2: ";
  cin >> lat2 >> long2;
  distance = computeDist(toRadian(lat1), toRadian(long1), toRadian(lat2),
   toRadian(long2));
   cout << "Distance = " << distance << endl;
    }
 
Check if a number is prime
 
#include 
#include
int smalldiv (int n) 
{
  int count; 
  count = 2;
  while (count < n && n % count != 0) 
  {
    count = count + 1;
  }
  return(count);
}
int main () 
{
  int n;
  cout << "Enter a natural number: ";
  cin >> n;
  if (n == smalldiv(n)) 
 {
    cout << n << " is a prime number" << endl;
  }
  else 
  {
    cout << n << " is not a prime number" << endl;
  }
  return(0);
}
 
Faster but probabilistic way
 
#include 
#include
#include 
#include 
int fermattest (int n) 
{
  int a;
  a = rand() % n;
  cout << "Trying with " << a << endl;
  return (a == (int(pow(a,n)) % n));
}
int main () 
{
  int n, i;
  cout << "Enter a natural number: ";
  cin >> n;
  cout << "How many trials?: ";
  cin >> i;
  srand(n*i);
  while (i > 0) 
  {
    if (fermattest(n)) 
    {
      i = i-1;
    } 
    else {
      cout << "The number " << n << " is definitely not prime." << endl;
      return(0);
    }
  }
  cout << "The number " << n << " is probably prime." << endl;
  return(0);
}

No comments:

Post a Comment