Tuesday, December 2, 2014

C++ using function pro



Avoid stupid C++ behavior in case of overflow
 
#include 
#include
#include 
#include 
int fermattest (int n) 
{
  int a, result, i;
  a = rand() % n;
  cout << "Trying with " << a << endl;
 return (a == (int(pow(a,n)) % n)); 
  result = 1;
  i = n;
  while (i > 0) 
  {
    result = (result * a) % n;
    i = i-1;
  }
  return (a == result);
}
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);
}
 
Understanding call-by-value and call-by-reference
 
#include 
#include
int f1 (int, int, int);
int f2 (int&, int&, int&);
int f3 (int, int&, int);
void main () 
{
  int i, j, k;
  i=1;
  j=2;
  k=3;
  cout << endl;
  cout << "Initial values of i, j, and k are: " 
    << i << ", " << j << ", and " << k << endl << endl;
  cout << "f1(i,j,k) = " << f1(i,j,k) << endl;
  cout << "Values of i, j, and k after the call to f1 are: " 
    << i << ", " << j << ", and " << k << endl << endl;
  cout << "f2(i,j,k) = " << f2(i,j,k) << endl;
  cout << "Values of i, j, and k after the call to f2 are: " 
    << i << ", " << j << ", and " << k << endl << endl;
  cout << "f3(i,j,k) = " << f3(i,j,k) << endl;
  cout << "Values of i, j, and k after the call to f3 are: " 
    << i << ", " << j << ", and " << k << endl;
}
int f1 (int x, int y, int z)
          {
  x=x+5;
  y=y+5;
  z=z+5;
  return(x+y+z);
}
int f2 (int& x, int& y, int& z) 
{
  x=x+5;
  y=y+5;
  z=z+5;
  return(x+y+z);
}
int f3 (int x, int& y, int z) 
{
  x=x+5;
  y=y+5;
  z=z+5;
  return(x+y+z);
}
 

No comments:

Post a Comment