
Understanding Prime Numbers Using Loop in Programming
Introduction Prime numbers are one of the most important concepts in mathematics and programming. They are widely used in algorithms, cryptography, and problem-solving. In this blog, we will learn what a prime number is and how to write a program using loops to check whether a number is prime. What is a Prime Number? A prime number is a number that is divisible only by: 1 Itself Examples: 2, 3, 5, 7, 11 → Prime numbers Non-Prime Numbers: 4 (divisible by 2) 6 (divisible by 2 and 3) Logic Behind Prime Number Program To check if a number is prime: Take a number as input Check divisibility from 2 to n-1 If any number divides it → Not Prime If no number divides it → Prime Java Program Using Loop import java.util.Scanner ; public class PrimeNumber { public static void main ( String [] args ) { Scanner sc = new Scanner ( System . in ); System . out . print ( "Enter a number: " ); int num = sc . nextInt (); int count = 0 ; for ( int i = 1 ; i <= num ; i ++) { if ( num % i == 0 ) { count ++; }
Continue reading on Dev.to Tutorial
Opens in a new tab




