0

program to find prime number

25th Sep 2016, 4:05 PM
Kabeer
Kabeer - avatar
2 Antworten
+ 2
C++ program to check whether a number is prime or not #include <iostream> using namespace std; int main() { int n, i, flag=0; cout << "Enter a positive integer: "; cin >> n; for(i=2;i<=n/2;++i) { if(n%i==0) { flag=1; break; } } if (flag==0) cout << "This is a prime number"; else cout << "This is not a prime number"; return 0; } Output _________________________ Enter a positive integer: 29 This is a prime number. _________________________ Enter a positive integer: 12 This is not a prime number.
25th Sep 2016, 4:50 PM
Driss Baidou
Driss Baidou - avatar
+ 1
https://code.sololearn.com/cWlQ6WzcAT1g #include <iostream> #include <math.h> using namespace std; bool isPrime(unsigned int n) { unsigned int i; double sqrtn; if (n < 2) { return false; } sqrtn = sqrt(n); for (i = 2; i <= sqrtn; i++) { if (n % i == 0) { return false; } } return true; } int main() { unsigned int n; cout << "Enter a number to check if it is prime: "; cin >> n; cout << n << endl; cout << n << " is " << (isPrime(n)? "" : "not ") << "prime." << endl; return 0; } And if you want to print the first prime numbers: https://code.sololearn.com/cMoVkbtiyUu4
25th Sep 2016, 5:28 PM
Zen
Zen - avatar