Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program, that uses the following algorithm, as part of a function, to de

ID: 645527 • Letter: W

Question

Write a program, that uses the following algorithm, as part of a function, to determine if a number n?2 is a

power of 2, such as 2^1=2, 2^3=8 or 2^10 =1024 but not 2^4- 3 = 13. To do this, you need to repeatedly attempt to divide n by 2^k, where k= 1, 2, 3, ... until n is either found to be divisible by 2k or 2k>n. The function returns true if n is a power of 2 and false otherwise.The result, either yes or no, is output to the screen.

The value n, is entered, via the keyboard, by the user. Your submission should include a screenshot ofthe execution of the program using each of the values n= 2, 3, 4, 5, 10, 16, 35, 101 and 128.

Using C++

Explanation / Answer

#include<iostream>
#include <math.h>

using namespace std;

bool isDivisible(int n){
   int i = 1;
   while(pow(2, i) <= n){
       if(n % (int)pow(2, i) != 0){
           return false;
       }
       ++i;
   }
   return true;
}

int main(){
   int num;
   while(true){
       cout << "Enter a number(-1 to exit): ";
       cin >> num;
       if(num == -1){
           break;
       }
       if(isDivisible(num)){
           cout << num << " is a power of 2" << endl;
       }
       else{
           cout << num << " is not a power of 2" << endl;
       }
   }
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote