// returns 1 if n is prime, 0 otherwise
void isPrime(const int n) {
// We know that if n is composite, then we will find a factor in the range [2,sqrt(n)]
// so we compute the square root only once to limit our number of calculations.
const int sqrt_n = sqrt(n);
// Iterate through possible factors
int i;
for( i = 2; i <= sqrt_n; ++i ) {
// If n is divisible by i (n%i==0) then we have a factor
if(!(n % i)) {
return 0;
}
}
// If we get here, we know n has no factors other than itself and 1
return 1;
}
Chat with our AI personalities
Loop through some numbers - for example, 2 through 100 - and check each one whether it is a prime number (write a second loop to test whether it is divisible by any number between 2 and the number minus 1). If, in this second loop, you find a factor that is greater than 1 and less than the number, it is not a prime, and you can print it out.
how to print "square" using for loop
Oh, dude, to print those numbers in QBasic, you can use a simple loop. Just loop from 1 to 5 and print the numbers with spaces in between. It's like making a sandwich, but with numbers instead of bread and cheese. So, like, don't stress, just code it up and hit run. Easy peasy, right?
Move the print out requesting the user to enter an integer outside of the for loop and it will only print once instead of each time around the loop. You'll need a way to save the even and odd numbers that you detect in the loop. One way is to have separate arrays to hold the even and the odd numbers as you go around the loop. Then at the end of the loop you can have more loops to print the contents of one array and then the contents of the other array. Another way is to concatenate the number onto separate Strings (even and odd) to be displayed after the data gathering loop.
n=100 loop until n = 9 print n n = n -1 end loop