Skip to main content

C++ = Code to check number is a prime or not. If not find the nearest prime number.

Code: 
#include <iostream>
using namespace std;
bool prime(int n)
{
if (n<=1)
{
return false;
}

       for (int i=2;i<=n/2;i++)
   {
      if (n%i==0)
  {
  return false;
  }
   }    
    return true;
}

int nearest(int n)
{
for (int i=n-1;i>=2;i--)
{
if (prime(i))
{
return i;
}
}
return 0;
}

int main ()
{
int number;
cout<<"Enter any number : ";
cin>>number;
if (prime(number))
{
cout<<"The number is prime. "<<endl;
}
    else
    {
    cout<<"The entered number is compositive."<<endl;
    cout<<"The nearest prime number will be "<<nearest(number)<<endl;
}

}
Result:



Comments

Popular posts from this blog

C++ = Multiplication of 2 matrices of order m*n by taking input by user.

Code: #include <iostream> using namespace std; int main() { int rows1,columns1,rows2,columns2; cout<<"Enter the rows of first column : "; cin>>rows1;     cout<<"Enter the columns of first column : ";     cin>>columns1;          cout<<"Enter the rows of second column : ";     cin>>rows2;     cout<<"Enter the columns of second column : ";     cin>>columns2;     int matrix1[rows1][columns1],matrix2[rows2][columns2];          if (rows2==columns1)     {     cout<<"Enter the elements of first matrix : ";     for (int i=0;i<rows1;i++)     {     for (int j=0;j<columns1;j++)     {     cin>>matrix1[i][j]; } }          cout<<"Enter the elements of second matrix : ";     for (int i=0;i<...

C++ = Code for checking any digit palindrome number

Code no: 1 = Using only main function to perform task. #include <iostream> using namespace std; int main() { int number,original,digit,reverse=0; cout<<"Enter any number : "; cin>>number; original=number; while (number!=0) { digit=number%10; reverse=(reverse*10)+digit; number=number/10; } if (original==reverse) { cout<<"This "<<original<<" is Palindrome number."; } else { cout<<"The "<<original<<" is not Palindrome number."; } } Result: Code no: 2 = Using two functions to perform same task. #include <iostream> using namespace std; int isprime(int num) { int digit=0,reverse=0; while (num!=0) { digit=num%10; reverse=(reverse*10)+digit;  num/=10; } return reverse; } int main() { int num; cout<<"Enter any digit to find its sum = "; cin>>num;          int original=num;          if (i...