This is a C++ program to determine whether a given number is prime or composite. The program first prompts the user to enter a number and stores it in the variable "i". It then initializes "n" to 2 and "prime" to 0.
The program then enters a while loop that checks if "n" is less than "i". If "i" is divisible by "n" (i.e., if "i%n" is 0), the program increments the "prime" variable. The loop then increments "n" by 1. Once the loop has finished, the program checks whether "prime" is equal to 0. If it is, the program prints "This number is Prime"; otherwise, it prints "This number is Composite".
Overall, this program checks every number from 2 to (i-1) to see if i is divisible by any of them. If i is not divisible by any number in that range, then it is prime. However, note that the program could be optimized by only checking up to the square root of i instead of i-1. Also, if i is less than 2, the program would incorrectly identify it as prime.
#include<iostream> using namespace std; int main() { int i,n=2,a,prime=0; cout<<"\nEnter the number:"; cin>>i; while(n<i) { if(i%n==0) { prime++; } n++; } if(prime==0) { cout<<"\nThis number is Prime"; } else { cout<<"\nThis number is Composite"; } return 0; }To download raw file Click Here
Enter the number:10 This number is Composite
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions