Practice 3: Primes Chapter2, Prob. 4: doubly-nested loop Write a program that fi
ID: 3749626 • Letter: P
Question
Practice 3: Primes Chapter2, Prob. 4: doubly-nested loop Write a program that finds and prints all of the prime numbers between 3 and 100. A prime number is a number such that one and itself are the only numbers that evenly divide it (e.g. 3,5,7,11,13,17, ...). Output: 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 Practice 3: Hint One way to solve this problem is to use a doubly-nested loop. The outer loop: iterates from 3 to 100 The inner loop: checks to see if the counter value for the outer loop is prime One way to see if number n is prime is to loop from 2 to n-1 and if any of these numbers evenly divides n then n cannot be prime. If none of the values from 2 to n-1 evenly divide n, then n must be prime. (Note that there are several easy ways to make this algorithm more efficient).Explanation / Answer
//practice 3 with output
#include <iostream>
using namespace std;
int main()
{
/*int numbers[] = { 10,20,30 };
test_example(numbers, numbers + 3);
test_result(numbers, numbers + 3);*/
int prime = 0,num,i =3;
while(i<=100)
{
num = 2;
prime = 1;
while (num < i)
{
if (i%num == 0)
{
prime = 0;
break;
}
++num;
}
if (prime)
{
cout << num << " ";
}
i++;
}
cout << endl;
return 0;
}
/*output
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
*/
-----------------------------------------------------------------------------
//Guess number
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int number, guess,trial=1;
//generate random number between 0-100
//initializa random number generation
srand(time(NULL));
number = rand() % 100 + 1;
do
{
cout << "Trial " << trial++;
cout << " Enter a guess between 1 and 100: ";
cin >> guess;
if (guess == number)
{
cout << "Your guess is right!!" << endl;
break;
}
if (guess < number)
{
cout << "Your guess is smaller than the secret number" << endl;
}
else
{
cout << "Your guess is larger than the secret number" << endl;
}
} while (guess != number);
}
/*output
Trial 1
Enter a guess between 1 and 100: 50
Your guess is larger than the secret number
Trial 2
Enter a guess between 1 and 100: 45
Your guess is larger than the secret number
Trial 3
Enter a guess between 1 and 100: 20
Your guess is smaller than the secret number
Trial 4
Enter a guess between 1 and 100: 30
Your guess is smaller than the secret number
Trial 5
Enter a guess between 1 and 100: 35
Your guess is right!!
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.