Yeah well how would I check if a variable was a multiple of 3 thanks
Bye
Shanedudddy2!
Printable View
Yeah well how would I check if a variable was a multiple of 3 thanks
Bye
Shanedudddy2!
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;
}
Sorry, but I just have to say this. This thread seems may too easy:p
Is that above solution more complicated than it has to be? Yes. Is that just the way I am? Yes.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:
Can you tell I'm in favor of the contest idea to obfuscate a simple problem as much as possible?:p Oh my, I am bored. I need to find something better to do. *walks away*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;
LOL. Yea I'd say Josh is a little bored right now.
pwned :pCode:#include<iostream>
int main
(){int
foobar; std::cout<<
"foobar is "
<<
(foobar%3?
"not ":"")
<<"a multiple of 3."
<< std::endl; return
0;
}
For additional speed, you could use a look-up table, i.e. precompute the values.
This solution might be a little memory-intensive, though.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];
}
#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; }