What's wrong with the codes I have written?
In my assignment I am given a test code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include<iostream>
#include<cassert>
#include"Number.h"
using namespace std;
int main(int argc, char * argv[])
{
Number nine(9);
assert(!nine.isPrime());
assert( nine.isDivisibleBy(1));
assert(!nine.isDivisibleBy(2));
assert( nine.isDivisibleBy(3));
assert(!nine.isDivisibleBy(8));
assert( nine.isDivisibleBy(9));
Number seven(7);
assert( seven.isPrime());
assert( seven.isDivisibleBy(1));
assert(!seven.isDivisibleBy(2));
assert(!seven.isDivisibleBy(3));
assert( seven.isDivisibleBy(7));
NumberseventySeven(77);
assert(!seventySeven.isPrime());
Number seventyThree(73);
assert(seventyThree.isPrime());
Number twentySeven(27);
assert(!twentySeven.isPrime());
assert(!twentySeven.isDivisibleBy(2));
assert(twentySeven.isDivisibleBy(3));
assert(twentySeven.isDivisibleBy(9));
cout << "All tests passed.\n";
}
|
I have to develop a class called "Number" that represents an integer value. The class should have a constructor that takes the integer value as its only argument. The constructor should store this value in a private member variable. Here is what I am able to come up with so far.
1 2 3 4 5 6 7 8 9 10
|
class Number
{
private:
int val;
public:
Number(int);
bool isPrime();
bool isDivisibleBy(int);
};
|
What do I have to add to the class code?
The second part of my question is that I have to define a public member function called "isPrime" that takes no argument and returns a bool. If the number is a prime number, then isPrime returns true, otherwise it returns false.
I also have to define another member function called isDivisibleBy that takes a single integer argument and returns a bool. If the integer is passed into "isDivisibleBy" is a divisor for the number, then the function returns true, otherwise it returns false. Here's what I came up with
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include "Number.cpp"
#include <cmath>
Number::Number(int a){
val = a;
}
bool Number::isPrime(){
int a = this->val;
if(a==1)
return false;
if(a==2)
return true;
int sq = sqrt(a);
for(int i=2;i<sq;i++){
if(a%i==0)
return false;
}
return true;
}
bool Number::isDivisibleBy(int d){
if(this->val % d == 0)
return true;
return false;
}
|
When I test the codes I get that " assert( seven.isPrime()); " failed. What did I do wrong? Thanks.