Java برنامج للتحقق من الرقم الأولي
ما هو الرقم الأولي؟
العدد الأولي هو عدد لا يقبل القسمة إلا على 1 أو على نفسه. على سبيل المثال، العدد 11 لا يقبل القسمة إلا على 1 أو على نفسه. الأعداد الأولية الأخرى 2، 3، 5، 7، 11، 13، 17...
ملاحظة: 0 و 1 ليسا عددين أوليين. 2 هو العدد الأولي الزوجي الوحيد.
Java برنامج لمعرفة ما إذا كان الرقم أوليًا أم لا
منطق البرنامج:
- نحتاج إلى تقسيم رقم الإدخال، مثل 17، من القيم من 2 إلى 17 والتحقق من الباقي. إذا كان الباقي 0 فالرقم ليس أوليًا.
- لا يوجد رقم يقبل القسمة على أكثر من نصف نفسه. لذلك نحن بحاجة إلى حلقة من خلال فقط
numberToCheck/2. إذا كان الإدخال 17، فإن النصف هو 8.5 وستتكرر الحلقة عبر القيم من 2 إلى 8 - إذا كان numberToCheck قابلاً للقسمة تمامًا على رقم آخر، فسيتم تعيين العلامة isPrime على
falseويتم الخروج من الحلقة.
public class PrimenumberToCheckCheck {
public static void main(String[] args) {
int remainder;
boolean isPrime=true;
int numberToCheck=17; // Enter the numberToCheckber you want to check for prime
//Loop to check whether the numberToCheckber is divisible any numberToCheckber other than 1 and itself
for(int i=2;i<=numberToCheck/2;i++)
{
//numberToCheckber is divided by itself
remainder=numberToCheck%i;
System.out.println(numberToCheck+" Divided by "+ i + " gives a remainder "+remainder);
//if remainder is 0 than numberToCheckber is not prime and break loop. Else continue the loop
if(remainder==0)
{
isPrime=false;
break;
}
}
// Check value true or false, if isprime is true then numberToCheckber is prime otherwise not prime
if(isPrime)
System.out.println(numberToCheck + " is a Prime numberToCheckber");
else
System.out.println(numberToCheck + " is not a Prime numberToCheckber");
}
}
الناتج المتوقع:
17 Divided by 2 gives a remainder 1 17 Divided by 3 gives a remainder 2 17 Divided by 4 gives a remainder 1 17 Divided by 5 gives a remainder 2 17 Divided by 6 gives a remainder 5 17 Divided by 7 gives a remainder 3 17 Divided by 8 gives a remainder 1 17 is a Prime numberToCheckber
تحقق من برنامجنا للعثور على رئيسي Numbers من 1 ل100
