Write a program to determine if a natural number has only 2 and/or 3 as prime fa
ID: 3549652 • Letter: W
Question
Write a program to determine if a natural number has only 2 and/or 3 as prime factors
and how many of each factor (2 and 3) it does have. Write your program from scratch
(you can reference other examples to get started with the basic structure of a program)
and name it prime23.cpp. The program should meet the following requirements:
a. Prompt (print a message to the user) to enter a natural number. [i.e. use cout]
b. Receive the integer input from the user. [i.e. use cin ]
c. Implement your algorithm (using while loops and if statements).
d. Print either
Explanation / Answer
#include <iostream>
using namespace std;
int main() {
int n;
//the natural number.
cin>>n;
int ct2=0,ct3=0;//count of factors of 2 and 3.
//checking 2
while(n%2==0){
n/=2;ct2++;
}
while(n%3==0){
n/=3;ct3++;
}
// 2 and 3 as prime factors and ct2>0 or ct3>0 assuring that original n has atleast one of these factors.
if((ct2+ct3>0)){
cout<<"Yes"<<" "<<"twos = "<<ct2<<" "<<"threes = "<<ct3<<endl;
}
else cout<<"No"<<endl;
return 0;
}
//the condition there would be that final n would have to be 1 which means after dividing n by 2's //and 3's if we are left with 1 , we can say that it had just 2 and 3 as prime factors.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.