For C++:
a) Write a function is_prime that takes a positive integer X and returns 1 if X is a prime number, or 1 if X is not a prime number.
b) write a program that takes a positive integer N and prints all prime numbers from 2 to N by calling your function is_prime from part a.
#include <iostream> using namespace std; int is_prime(int num) { int i; if (num <= 1) return 0; if (num % 2 == 0 && num > 2) return 0; for (i = 3; i < num / 2; i += 2) { if (num % i == 0) return 0; } return 1; } int main(){ int n; cout<<"Enter a number: "; cin>>n; cout<<"Primes from 2 to "<<n<<" are:"<<endl; for(int i = 2;i<=n;i++){ if(is_prime(i)){ cout<<i<<endl; } } return 0; }
Get Answers For Free
Most questions answered within 1 hours.