Answer to Question #25671 in C++ for Zulaikha

Question #25671
Implement a class in C++ programming named MyInteger. The class contains:
An int data field named value that stores the int value represented by this object.
A constructor that creates a MyInteger object for the specified int value.
A get function that returns the int value.
Functions isEven(), isOdd(), isPrime() that return true if the specified value is even, odd, or prime, respectively
Static functions isEven(int), isOdd(int), isPrime(int) that return true if the specified value is even, odd, or prime, respectively
Static functions isEven(MyInteger), isOdd(MyInteger), isPrime(MyInteger) that return true if the specified value is even, odd, or prime, respectively
Functions equals(int) and equals(MyInteger) that return true if the value in the object is equal to the specified value. A static function parseInt(string) that converts a string to an int value.

Write a C++ program that tests all functions in the class.
1
Expert's answer
2013-03-05T09:14:20-0500
#include<math.h>
# include <iostream>
# include <stack>
# include <string>
int charToInt(char c){
switch (c){
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
default: return 0;
}
}
class MyInteger{
protected:
int val;
public:
MyInteger(){val=0;}
MyInteger(int a){val=a;}
int& get(){return val;}
bool isEven(){if (val%2==0) return 0; else return 1;}
bool isOdd(){if (val%2==0) return 1; else return 0;}
bool isPrime(){if (val%2==0) return false;
for (int i=0;i< static_cast<int>(sqrt(static_cast<double>(val)));i+=2){
if (val%i==0) return false;
}
return true;
}

friend bool isEven(MyInteger &a);
friend bool isOdd(MyInteger &a);friend bool isPrime(MyInteger &a);
bool equals(int &a){if (a==val) return true; return false;}
bool equals(MyInteger a){return (a.val==val) ? 1:0;}
void parseInt(string a) {
int len=a.length();
int temp=0,t=0;
for (int i=len-1;i>=0;i--){
t=t+charToInt(a[i])*10*temp;
temp++;
}
val=t;
}
};
bool isEven(MyInteger &a){if (a.val%2==0) return 0; else return 1;}
bool isOdd(MyInteger &a){if (a.val%2==0) return 1; else return 0;}
bool isPrime(MyInteger &a){if (a.val%2==0) return false;
for (int i=0;i< static_cast<int>(sqrt(static_cast<double>(a.val)));i+=2){
if (a.val%i==0) return false;
}
return true;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS