hiLo....and_gcd's

# hiLo....and_gcd's - /Requirements assert(j>0...

This preview shows pages 1–3. Sign up to view the full content.

hiLo…………and the gcd’s //===================================== //hiLo.cpp //Plays the high low game //===================================== #include <iostream> #include <cstdlib> using namespace std; int main(void) { int max=100;//max number for guessing int seed; cout<< "Input a seed integer please :> "; cin>> seed; //get a somewhat random number between zero and max; srand(seed); int target=rand()%(max+1); cout<< "Guess a number between 0 and " << max << " :> "; int guess; cin>>guess; while(guess!=target) { cout<<guess<<" < target is "<< (guess<target) << endl; cout<<guess<<" > target is "<< (guess>target) << endl; cout<< "Guess a number between 0 and " << max << " :> "; cin>> guess; } cout<<"Congratulations. " <<"You've just wasted a few minutes of your life"; cout<<endl; return 0; } int gcd(int i,int j) { int g=j; while((i%g)!=0 and (j%g)!=0) { g=g-1; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
hiLo…………and the gcd’s return g; } #include <cassert> using namespace std; int gcd(int i, int j)
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: { //Requirements assert(j>0); assert(i>=0); int g=j; while(not((i%g)==0 and (j%g)==0 )) { g=g-1; } return g; } //=========================================================== //gcd3.cpp //Computes the greatest common divisor of two non-negative //integers a and b without dividing numbers //=========================================================== #include <cassert> using namespace std; int gcd(int a, int b) { assert(not(a==0 and b==0));//they can't both be zero assert(a>=0); assert(b>=0); int i=a;//make local copies int j=b; while((i!=j) and (j!=0) and (i!=0)) { //loop invariant gcd(i,j)=gcd(a,b) if(i>j) { i=i-j;//reduce i but leave GCD unchanged } else { j=j-i;//reduce j but leave GCD unchanged } } //Now only special cases are possible hiLo…………and the gcd’s if(i==0) //GCD(0,j)=j { return j; } return i; //GCD(i,i)=i or GCD(i,0)=i }...
View Full Document

## This note was uploaded on 11/06/2011 for the course HANDOUT 502 at USC.

### Page1 / 3

hiLo....and_gcd's - /Requirements assert(j>0...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online