[C++] Write a console program that asks the user to enter a positive integer gre
ID: 3927089 • Letter: #
Question
[C++]
Write a console program that asks the user to enter a positive integer greater than 1. The program computes the prime factors of the number and prints them. For example, if the user enters 100, the program displays 2 2 5 5.
Develop 8 test cases and verify that your program runs correctly for them. The test cases should contain some prime numbers as well as non-prime numbers. Include tests for edge cases, such as the numbers 2 (the first prime) and 4 (the first non-prime). Develop test cases that try to break your program so that you are sure your code is correct.
Include a description of your test cases in a multi-line comment near the top of your source code. Make sure the comment is nicely organized and easy to read and understand.
Explanation / Answer
/*
The test cases tried are:
2 --> First prime
-1 --> Negative number
1 --> No factors other than itself
4 --> Whole square of a prime
100 -> Whole square of a composite number
*/
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a positive number:";
cin>>n;
if(n<0)
{
cout<<"You can only enter a positive interger."<<endl;
return 1;
}
int tmp=n;
for(int i=2;i<n&&tmp>0;i++)
{
while(tmp%i==0)
{
cout<<i<<' ';
tmp = tmp/i;
}
}
cout<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.