Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check prime with and without recursion in java #1417

Merged
merged 10 commits into from
Dec 2, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Java/cp/Prime.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//check whether a number is Prime or not without recursion//
import java.util.Scanner;
class Prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int n=(int)Math.abs(sc.nextInt());
int c=0;
for(int i=2;i<n;i++)
if (n%i==0)
c++;
System.out.println(n+((c==0)?" is a Prime Number." :" is not a Prime Number."));
}
}
//* Contributed By ErzaTitani-2001
/* Sample Input and Output :
Input :
Enter a number : 13
Output :
13 is a Prime Number.
Space Complexity : O(1)
Time Complexity : O(n) */

32 changes: 32 additions & 0 deletions Java/cp/PrimeRecursion.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//check whether a number is Prime or not with recursion//
import java.util.Scanner;
class PrimeRecursion
{
public static int prime(int n,int div)
{
if(div<n)
{ if(n%div!=0)
prime(n,div+1);
else
return 0;
}
return 1;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int n=(int)Math.abs(sc.nextInt());
int c=prime(n,2);
System.out.println(n+((c!=0)?" is a Prime Number." :" is not a Prime Number."));
}
}
//* Contributed By ErzaTitani-2001
/* Sample Input and Output :
Input :
Enter a number : 13
Output :
13 is a Prime Number.
Space Complexity : O(n)
Time Complexity : O(n) *///