Yeah well how would I check if a variable was a multiple of 3 thanks

Bye

Shanedudddy2!

Printable View

- 01-11-2003Shanedudddy2How to check if a multiple of 3?
Yeah well how would I check if a variable was a multiple of 3 thanks

Bye

Shanedudddy2! - 01-11-2003foniks munkee
If the number is divisible by three then it is a multiple of 3. Try testing to see if when the number is divided by 3 there is a remainder using the modulus operator.

Code:`#include <iostream>`

using std::cout;

using std::endl;

int main(void)

{

int foobar = 10;

if ((foobar % 3) == 0)

cout << "foobar is a multiple of 3" << endl;

else

cout << "foobar is not a multiple of 3" << endl;

return 0;

}

- 01-11-2003joshdick
Sorry, but I just have to say this. This thread seems may too easy:p

Code:`int foobar;`

if(!(foobar % 3))

cout << "foobar is a multiple of 3" << endl;

else

cout << "foobar is not a multiple of 3" << endl;

Another way to do this. If a number is divisible by three, the sum of its digits is divisible by three. ex: 121233666995123172990021 is divisible by three, and I know this rather easily by just adding up the digits. You could read in a number as a char array, convert it to an int array, then add up the numbers. You may be thinking "but, then, you'd still have to use the modulus operator!". Not true. If you really wanted a difficult, non-elegant solution, you could do this:

Code:`while(foobar >= 0)`

{

foobar -= 3;

}

if(!foobar) // if(foobar == 0)

cout << "foobar is a multiple of 3!" << endl;

else

cout << "foobar is not a multiple of 3." << endl;

- 01-11-2003Munkey01
LOL. Yea I'd say Josh is a little bored right now.

- 01-11-2003Polymorphic OOPCode:
`#include<iostream>`

int main

(){int

foobar; std::cout<<

"foobar is "

<<

(foobar%3?

"not ":"")

<<"a multiple of 3."

<< std::endl; return

0;

}

- 01-12-2003Sang-drax
For additional speed, you could use a look-up table, i.e. precompute the values.

Code:`int main()`

{

bool* Div3Array = new bool[std::num_limits<int>::max()];

for (int i=0;i<std::num_limits<int>::max();++i)

Div3Array[i] = i%3==0; //or another algorithm

//Now we can use the array to determine if an arbitrary

//number is divisible with 3

int num;

cin >> num;

cout << Div3Array[i];

}

- 01-12-2003beege31337
#define XX goto

#define O int

O main(){O o;cin>>o;x: if(--o<2||o--==--o)

XX X;XX x;X: cout<<(--o==-2?"yes":"no");

return 0; }