using loops

0 Barima Appiah-Dankwa · September 18, 2015
how do i use loops for primetest

Post a Reply

Replies

Oldest  Newest  Rating
+1 Jon Z. · September 27, 2015

#include<stdio.h>

int isPrime(long num)
{
    if(num < 2)
    {
        return 0;
    }
    else if(num <= 3)
    {
        return 1;
    }
    else if (num % 2 == 0 || num % 3 == 0)
    {
        return 0;
    }

    long i;
    for (i = 5; i*i <= num; i++)
    {
        if(num % i == 0)
        {
            return 0;
        }
    }
    return 1;
}

int main(){
    int MAX_NUM = 100;
    int i;

    for(i=0; i<MAX_NUM; i++){
        if(isPrime(i)){
            printf("%d is prime\n", i);
        }
        else{
            printf("%d is not prime\n", i);
        }
    }

    return 0;
}
+1 Scott Walker · September 27, 2015

void checkIfPrime(int number)
{
    for (int i = 2; i < number; i++)
    {
        if (number % i == 0)
        {
            cout << "Number not prime" << endl;
            break;
        }
        else if (number % i != 0)
        {
            cout << "Number is prime" << endl;
            break;
        }
    }
}

That function should do it, number variable is user's input
0 Justin Zeyeum · September 27, 2015
Write c++ a program that asks user for an integer n ((n>0) and prints the numbers 1,2,3..n on individual rows. Use for-loop in the program.
0 Alan Masimba Walker · September 18, 2015
Have you got an attempt we can bug fix?
  • 1

C++

106,979 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator