question about conditional operator (?:)

Richard via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 26 06:09:28 PDT 2016


Hello all,

I've got a program that correctly computes the largest factor in 
the prime decomposition of a positive number:

*****************************************************
import std.math std.stdio;

ulong largestPrimeFactor(ulong n) {
     for(ulong p=2; p<=sqrt(cast(real)n); ) {
         if(n%p==0)
             n/=p;
         else
             p+=1;
     }
     return n;
}

void main() {
     writeln(largestPrimeFactor(4));
}
*****************************************************

However, if I replace the content of the for loop with the ?: 
operator, the program is not
correct anymore (largestPrimeFactor(4) now returns 3):

*****************************************************
import std.math std.stdio;

ulong largestPrimeFactor(ulong n) {
     for(ulong p=2; p<=sqrt(cast(real)n); ) {
         n%p==0 ? n/=p : p+=1 ;
     }
     return n;
}

void main() {
     writeln(largestPrimeFactor(4));
}
*****************************************************

What am I doing wrong here?
I'm using dmd version 2.071.1-0 on ubuntu.


More information about the Digitalmars-d-learn mailing list