| EZX (31) | |||
|
So i got a task asking to use "for" interval to show numbers from 1-100 which can be divided by 3, but CANNOT be divided by 2. Afterwards calculate the sum of all these numbers. I got this far but have no clue on the formula to show only numbers that can be divided by 3 and at the same time can't be divided by 2.
Any help appreciated. | |||
|
Last edited on
|
|||
| AleaIactaEst (99) | |||||
|
You can describe all numbers that can be divided by 3 with x = 3 * n, n being an integer. This value can only be divided by 2, if n is a multiple of 2, i.e. x = 3 * (2 * m), with m = n / 2. So if n is odd, x will be an integer that can be divided by 3, but can not be divided by 2. Examples: n = -1: x = 3*n = -3 < 1 n = 1: x = 3*n = 3 n = 3: x = 3*n = 9 n = 5: x = 3*n = 15 ... n = 33: x = 3*n = 99 n = 35: x = 3*n = 105 > 100 So you need to start the loop with n=1 and increase n by two after each time executing the loop
Edit: Of course you could alternatively run the loop from 1 to 100 and check each time if i can be divided by 2 and 3 using the modulo operator:
| |||||
|
Last edited on
|
|||||
| EZX (31) | |
|
Thanks alot im gonna try em out now. | |
|
Last edited on
|
|
| Chervil (812) | |
|
I suspect the use of the modulus operator is what is intended. Still, I was going to suggest start at 3, and then increment in steps of 6. | |
|
|
|
| EZX (31) | |
|
i am soo stupid for this if i do the 1st suggestion, after putting cout<<i im only getting a number "35" instead of 3, 9, 15 dasdasdsa my head hurts, lol | |
|
|
|
| AleaIactaEst (99) | |||
Try this:
| |||
|
|
|||
| EZX (31) | |
|
oh wow it worked! thanks wouldn't be able to do it without you. | |
|
|
|