GKED
GKED

Reputation: 410

for loop integrated in the argument field of an if statement in c++

I am working on solving a mathematical problem. What I am trying to do is to have an if statement that compares variable n to a set of variables i 1 through 10. Is there any way to do it in c++? here is what I am trying to do:

 int smallPos(int n){
     if (n%for(int i=1;i<=10;i++)==0) {
        return n;
      }

This is obviously wrong but is any way to get around it?

Upvotes: 1

Views: 117

Answers (2)

Z&#233;ychin
Z&#233;ychin

Reputation: 4205

It looks like you're trying to do this:

int smallPos(int n)
{
    return (n % 232792560 == 0) ? n : <sentinel value>; // sentinel_value is the value return if n does not meet requirements
    //232792560 is the first number for which n % a: a ∈ {1,2,3...10} This is faster than checking each of these values.
}

Upvotes: 4

Jesse Emond
Jesse Emond

Reputation: 7490

What you want to do is this:

int smallPos(int n)
{
    for (int i = 1; i <= 10; ++i)
    {
        if (n % i != 0) // check if n % i == 0, if not, then we shouldn't return n.
        { 
            return -1; // or whatever you want to return when not ALL the remainders are 0.
        }
    }

    return n; // If we get here then all the remainders were 0s.
}

Upvotes: 2

Related Questions