Write a program, using a function, that will check a single integer to determine if it is prime number or not.

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter6: User-defined Functions
Section: Chapter Questions
Problem 17SA: Write the definition of a function that takes as input two decimal numbers and returns first number...
icon
Related questions
Question
100%
1. Write a program, using a function, that will check a single integer to determine if it is prime
number or not.
Enter a positive integer enter to check:
X is not a prime number.
Or
X is a prime number.
Transcribed Image Text:1. Write a program, using a function, that will check a single integer to determine if it is prime number or not. Enter a positive integer enter to check: X is not a prime number. Or X is a prime number.
Expert Solution
Introduction

A number is said to be prime number if it has only two factors 1 and itself

Program

#include <iostream>

using namespace std;

bool isPrime(int n){
    int factors=0;      //variable to store number of factors
    
    for(int i=1;i<=n;i++){  //i from 1 to n
        if(n%i==0)          //if i exactly divides n
            factors++;      //i is factor of n so increment factors by 1
    }
    
    if(factors==2)      //if factors is 2
        return true;    //number is prime and return true
    else                //if factors is not 2
        return false;   //number is not prime and return false
}

int main()
{
    int x;
    cout<<"Enter a positve integer enter to check: ";
    cin >> x;           //input a number
    
    if(isPrime(x)){     //call the function and it returns true
        cout << x << " is a prime number";      //print message saying number is prime
    }
    else{               //if function call returned false
        cout << x << " is not a prime number";  //print a message saying number is not prime
    }
    return 0;
}

steps

Step by step

Solved in 3 steps with 1 images

Blurred answer
Knowledge Booster
Function Arguments
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning
C++ for Engineers and Scientists
C++ for Engineers and Scientists
Computer Science
ISBN:
9781133187844
Author:
Bronson, Gary J.
Publisher:
Course Technology Ptr