solutions14 - //POSTCONDITIONS: returns gcd of x and y {...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CSCI-1100 Computer Science I Rensselaer Polytechnic Institute Spring 2004 Studio 14 Exercises -- Solutions 1. #include <iostream> #include <cmath> using namespace std; // PUT FUNCTION isPrime HERE int main () //PURPOSE: find twin primes between 3 and 100 //PRECONDITIONS: none //POSTCONDITIONS: returns 0 for success { int k; // loop variable // try all numbers between 3 and 100 for (k=3; k<=98; k=k+2) { cout << k << " and " << k+2 << " are twin primes" << endl; } } return 0; } 2. #include <iostream> using namespace std; int gcd(int x, int y) //PURPOSE: Euclid's algorithm to compute gcd of x and y //PRECONDITIONS: 0 <= x, 0 <= y, x and y are ints
Background image of page 1

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

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: //POSTCONDITIONS: returns gcd of x and y { int r; // remainder // Euclid's Algorithm r = x % y; while (r != 0) { //INVARIANT: gcd(x,y) = gcd(y,r) x = y; y = r; r = x % y; } // return the result return y; } int main () //PURPOSE: test gcd function //PRECONDITIONS: none //POSTCONDITIONS: return 0 for success { int x,y; // numbers from user // get x and y from user cout &lt;&lt; &quot;Enter value for x (nonnegative): &quot;; cin &gt;&gt; x; cout &lt;&lt; &quot;Enter value for y (nonnegative): &quot;; cin &gt;&gt; y; // compute and display gcd cout &lt;&lt; endl; cout &lt;&lt; &quot;gcd(&quot; &lt;&lt; x &lt;&lt; &quot;,&quot; &lt;&lt; y &lt;&lt; &quot;) = &quot; &lt;&lt; gcd(x,y); cout &lt;&lt; endl; return 0; }...
View Full Document

Page1 / 2

solutions14 - //POSTCONDITIONS: returns gcd of x and y {...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online