'How to solve the problem to find least prime number from 1 to 100 and if there is better than this code please kindly update it
I was trying to get Smallest Prime Number(p) by dividing it with set of Distinct (n) Natural Numbers where (q) is the Least Natural Number and the Remainder should be q.
Constraints are 1<n<100 and p<100.
Example 1:
input (n): 3 4 5 1
output (p): 61
Explanation:
Here n+1 numbers are 3,4,5 and 1 where q = 1(is the least natural number).
The smallest number is 1 which leaves remainder 1 when divided by 3, 4 and 5 is 61 and is Prime. Hence output is 61.
Example 2:
input (n): 3 4 5 2
output (p): None
Explanation:
Here q=2. Any number that when divided by 4 leaves remainder 2 must be an even number e.g. 6,10,14 etc.
Hence it can't be prime .
Hence the output is None
Here is my code:
import java.util.*;
public class Main{
public static void main(String [] args){
int[] n = {3,4,5};
int q =1,i,temp1 = 0,p;
String temp =new String("None");
for(p=3;p<100;p++){
if(p%n[0] == q && p%n[1] == q && p%n[2] == q)
temp1 = p;
}
if(temp1%n[0] == q && temp1%n[1] == q && temp1%n[2] == q)
System.out.println(temp1);
else
System.out.println(temp);
}
}
Input : 3,4,5,1
Output is 61.
Solution 1:[1]
Your code is sort of lumped together. It would facilitate the process and make it easier to debug if you broke it up into methods. But don't be prompting for input during the test phase. Hardcode an array of ints with which to test.
I suggest writing two methods.
the first method ( e.g.
isPrime) is to determine if a value is a prime. There are many good answers on this site on how to compute primes. Just do a search.then initialize the smallest prime to
Integer.MAX_VALUE(which is also a prime)the second method simply calls the first with a candidate and does the following:
- if the
isPrimemethod returns true,- compare it to the smallest prime.
- if smaller, assign to smallest prime, else ignore.
- if the
isPrimemethod returns false, ignore.
- if the
when you're done, you will have the smallest prime
By breaking the code into methods you can focus on one thing at a time. The isPrime method will be the more complicated of the two. Make certain you use print statements to help in the debug process.
here are some things to consider.
- to check if
Nis a prime, only check remainders of divisors from2to thesqrt(N). - you can first try
2and then continue with3thrusqrt(N)incrementing by2.
You may want to check out the Sieve of Eratosthenes as alternative to finding primes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
