Вопрос

Just for kicks and giggles, would it be possible to put a 'for' loop inside a ternary operation?

Here's code for finding if a number is prime:

int isPrime(int number){
 int i, root = sqrt(number)+1; 

 if(number==1||!(number)||!(number&1)) return 0;            
 if(number==2)                         return 1;
 for(i=3;i<root;i+=2) if(!(number%i))  return 0;

 return 1;

}

Here's the beginning of my "thought":

 int isPrime(int number){
      return number&1 || !(number&1) || number==2 ? 0:1;
 }

would it be possible to add the for loop check in there?

Это было полезно?

Решение

No, because the format of a ternary operator is:

condition ? first_expression : second_expression;

While a for loop is not an expression - it is a statement (as in, it does not evaluate to a result)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top