I'm doing the program for SPOJ.com taks which should recognize Prime number. Unfortunately this SPOJ taks is in Polish language, hence I will try to translate what should be the input and outpu expectation:
Input:
n - the number of tests n <100000, in the next lines n numbers from the interval [1..10000]
Output:
For each number of the word "YES", if this number is prime. Word: "NO", otherwise.
Example:
Input:
3
11
1
4
Output:
YES
YES
NO
I wrote following code whcih during the test works perfectly fine. Unfortunately when I'm trying to submit this code on SPOJ webpage it is constantly returning me error "
runtime error (NZEC)" Can someone advise how I can improve it?
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(1<=n&& n<=100000){
for(int i = 0; i<n+1; i++){
int v = in.nextInt();
if(1<=v&&v<=10000){
if(isPrime(v) == true){
System.out.println("YES");
}
if(isPrime(v) == false){
System.out.println("NO");
}
}
}
}
}
private static boolean isPrime(int v) {
if (v < 2) return true;
if (v == 2) return true;
if (v % 2 == 0) return false;
for (int i = 3; i * i <= v; i += 2)
if (v % i == 0) return false;
return true;
}
Have you learnt Sieve Method for Prime numbers.
Check here you will find the better solution.
public class PrimeSieve {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
// mark non-primes <= n using Sieve of Eratosthenes
for (int factor = 2; factor*factor <= n; factor++) {
// if factor is prime, then mark multiples of factor as nonprime
// suffices to consider mutiples factor, factor+1, ..., n/factor
if (isPrime[factor]) {
for (int j = factor; factor*j <= n; j++) {
isPrime[factor*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= n; i++) {
if (isPrime[n]) primes++;
}
System.out.println("The number of primes <= " + n + " is " + primes);
}
}
You should check all numbers from 2 to n, to see if the number isPrime or not.
Code
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n ; i++) {
int v = in.nextInt();
if (v >= 1 && v < 10000) {
if (isPrime(v) == true) {
System.out.println("YES");
}
if (isPrime(v) == false) {
System.out.println("NO");
}
}
}
}
private static boolean isPrime(int v) {
for(int i=2;i<v;i++) {
if(v%i==0)
return false;
}
return true;
}
}
I hope this helps you.
Related
Write a program to read n numbers. The first number specified as input will be n. Next, the program should read n integer numbers.
The program should check for each number if it is prime as well as if its reverse is prime.
Display all such numbers in ascending order.
Consider below example for input and output:
Input:
7
11
12
23
19
7
113
101
Output:
7
11
101
113
My code
public class Prime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int temp;
int[] a = new int [x];
int[] r = new int [x];
int[]c = new int[a.length+r.length];
int[] rev = new int [x];
for(int i=0;i<x;i++){
a[i] = sc.nextInt();
rev[i]=a[i];
}
for(int i = 0; i < a.length; i++) {
while(rev[i] != 0) {
r[i] = r[i] * 10;
r[i] = r[i] + rev[i]%10;
rev[i] = rev[i]/10;
}
}
for(int i = 0; i < a.length; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if((a[i]%j==0) || (r[i]%j==0)) {
isPrime = false;
break;
}
}
if(isPrime)
System.out.println(a[i]);
System.out.println(r[i]);
}
}
}
Somewhere I am stuck I don't know how to eliminate repeated no, how to merge the array at last and also it is printing 1 and 2 as prime no when I give input and 2
You need to use TreeSet - which will contain only distinct elements and give result in sorted form. You can refer to following code-
Set<Integer> set = new TreeSet<>();
for(int i = 0; i < a.length; i++) {
boolean isPrime = true;
if(isPrime(a[i]) && isPrime(r[i]))
set.add(a[i]);
}
Iterator it = set.iterator();
while(it.hasNext())
System.out.print(it.next() + " ");
Also create a function for checking prime numbers -
private static boolean isPrime(int num) {
if(num==1) return false;
for(int i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
You can try below code. Hope it helps you,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PrimeNumberTest {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(7, 11, 12, 23, 19, 7 ,113, 101));
//To remove duplicates
Set<Integer> set = new TreeSet<>(list);
System.out.println(getPrimeNumbers(set).toString().replaceAll(",", "").replace("]", "").replace("[", ""));
}
//Method to get unique ordered set of prime numbers
private static Set<Integer> getPrimeNumbers(Set<Integer> set) {
Set<Integer> resultList=new TreeSet<>();
set.forEach(ele->{
//check for prime
if(isPrime(ele)){
//if prime number check for reverse and if true, add to result
if(isPrime(reverserNumb(ele)))
resultList.add(ele);
}
});
return resultList;
}
private static boolean isPrime(int num){
if(num<2)
return false;
// Check for even numbers
if (num % 2 == 0) {
return num == 2;
}
// Check for odd numbers
for (int i = 3; i*i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static int reverserNumb(int num) {
return Integer.valueOf(new StringBuilder(String.valueOf(num)).reverse().toString());
}
}
Here is the code for prime test using √n approach
static boolean isPrime(int n){
//corner case
if (n <= 1) return false;
if (n <= 3) return true;
//middle 5 number
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
Use can use set for remove duplicate element
Try if this code works, hope it helps
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class PrimeNumbers {
static ArrayList<Integer> prime = new ArrayList<>();
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.print("Enter Number of Integers: ");
int number_count = user_input.nextInt();
int[] numbers = new int[number_count];
for (int i = 0; i < numbers.length; i++) {
System.out.print("Enter Integer: ");
numbers[i] = user_input.nextInt();
}
System.out.print("Values Entered: ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
checkPrime(numbers[i],false); //false don't reverse
checkPrime(numbers[i],true); //true reverse value to check if it is also prime
}
System.out.print("\nList of prime numbers: ");
Collections.sort(prime);
for(int n : prime){
System.out.print(n + " ");
}
if(prime.isEmpty()){
System.out.print("no prime numbers on list\n");
}
}
//check for duplicates
static void insertValueToPrime(int n){
for(int p : prime){
if(n == p){
return;
}
}
prime.add(n);
}
static void checkPrime(int n,boolean isReverse) {
int i, m = 0, flag = 0,realn = n;
if(isReverse){
n = reverseNumber(n);
}
m = n / 2;
if (n == 0 || n == 1) {
//no a prime number
} else {
for (i = 2; i <= m; i++) {
if (n % i == 0) {
// not a prime number
flag = 1;
break;
}
}
if (flag == 0) {
insertValueToPrime(realn);
}
}
}
static int reverseNumber(int n){
String reverse = "",str=""+n;
for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
return Integer.parseInt(reverse);
}
}
This program gets 4 input from the user and prints out all the pairs except for the duplicate pairs. I wanted it print only the pairs that sum equals a prime number. I did the entire program there is no compilation error but in the output it prints to all pairs except the duplicate pair(i want it to print only the pair whose sum= a prime number) can anyone tell me what i am doing wrong
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {
public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added
public static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
int inputs = 4;
input(inputs);
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
if(i != j)
System.out.println(numbers.get(i)+ " + " + numbers.get(j) + " = "+ isPrime(numbers.get(i) + numbers.get(j)));
}
} }
public static int isPrime (int sumPair)
{
boolean primeVal =true ;
if(sumPair < 2)
primeVal= false;
else if(sumPair ==2)
primeVal=true;
else if (sumPair % 2 == 0)
primeVal = false;
else
{
int stop = (int)Math.sqrt(sumPair);
for (int d = 3; d <= stop && primeVal; d = d + 2)
{
if (sumPair % d == 0)
primeVal = false;
}
}
return(sumPair);
}
public static void input(int inputNumbers)
{
while(numbers.size() < inputNumbers){ // while there is more inputs needed
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
if(num > 0) // if the input is valid
numbers.add(num);
else // if the input is not valid
while (num <= 0) { // while the input is not valid
System.out.print("Enter a positive integer: ");
num = input.nextInt(); // get the next int if it wasn't valid
if(num > 0) { // if the input gets valid
numbers.add(num);
}
}
System.out.println("Thank you.");
}
}
public static int sumPair(int num1, int num2)
{
return num1 + num2;
}
}
You go to a lot of trouble to compute a boolean primeVal which tells whether the input be true or false, but you never actually return this value. Try this instead:
public static boolean isPrime (int sumPair) {
boolean primeVal = true;
if (sumPair < 2 || sumPair % 2 == 0) {
primeVal = false;
}
else {
int stop = (int)Math.sqrt(sumPair);
for (int d=3; d <= stop; d += 2) {
if (sumPair % d == 0) {
primeVal = false;
break;
}
}
}
return primeVal;
}
Use this main() method:
public static void main (String args[]) {
int inputs = 4;
input(inputs);
for (int i=0; i < inputs-1; i++) {
for (int j=i+1; j < inputs; j++) {
boolean prime = isPrime(numbers.get(i) + numbers.get(j));
if (prime) {
System.out.println(numbers.get(i) + " + " + numbers.get(j));
}
}
}
}
Your condition to determine if you print the current pair or not is if(i != j), so it will only print if i is different from j (duplicate).
You made a nice isPrime function, you should call it.
You made your isPrime function return an int, and I'm pretty sure it should return a boolean instead. Also, it returns the argument you gave it, so it does virtually nothing except spend time in a potentially expensive operation. Perhaps should it return primeVal instead.
Your code should look like:
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
ni = numbers.get(i);
nj = numbers.get(j);
if(isPrime(ni+nj)){
System.out.println(ni + " + " + nj + " = "+ (ni + nj));
}
}
}
What this does is get the numbers for indexes i and j and store them in ni and nj respectively. Then, it checks it their sum is prime. If it is, then it prints the sum.
I'm not sure why my ct is not going all the way to 100 even though I clearly set it to go until it reaches 100.
public class PalindromicPrime
{
public static void main(String [] args)
{
int ct = 0;
while(ct < 100)
{
if(isPalindrome(ct) && isPrime(ct))
{
if(ct % 10 != 0)
{
System.out.print(ct + " ");
}
else
{
System.out.print("\n");
}
}
ct++;
}
public static boolean isPalindrome(int p)
{
int palindrome = p;
int reverse = 0;
while (palindrome != 0)
{
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (p == reverse)
{
return true;
}
return false;
}
I'm assuming my isPrime code is wrong since I'm getting a 4 in my output. What's wrong with this method?
public static boolean isPrime(int p)
{
for(int i = 2; i < p/2; i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
First change you should do in your method isPrime() is change this line
for(int i = 2; i < p/2; i++)
to
for(int i = 2; i <= p/2; i++) // you can easily find the reason why it is necessary(=)
And also you are printing palindromic numbers less than 100 which are prime,not first 100 palindrome numbers, if you want to print first 100 palindrome numbers you can take another counter which will keep track of the numbers printed.
You can modify your main method like this:
public static void main(String [] args)
{
int ct = 0,n=0; // n to count numbers printed/found
while(n < 100) // change the condition to check n<100
{
if(isPalindrome(ct) && isPrime(ct))
{
System.out.print(ct + " ");
if(n % 10 == 0)
{
System.out.println();
}
n++; // incementing n after a number is found!
}
ct++;
}
}
Your palindrome method is fine. It's your isPrime method that's not working because to check if a number is prime, you're supposed to test factors up to the square root of the number. So a simple change in the condition should do it,
public static boolean isPrime(int p)
{
for(int i = 2; i <= Math.sqrt(p); i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
Change your isPrime function to following (replace < with <= as 4/2 is 2 and loop will not run at all for p=4):
public static boolean isPrime(int p) {
for (int i = 2; i <= p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int ct = 2;
int count = -1;
while (count < 99) {
if (isPalindrome(ct) && isPrime(ct)) {
count++;
if (count % 10 == 0) {
System.out.print("\n" );
}
System.out.print(ct + " ");
}
ct++;
}
}
The only numbers that are palindrome and prime and less than 100 are:
1 2 3 5 7 11
Try changing the value of 100 to 102. Then you get the following output as 101 is the next palindromic prime after 11:
1 2 3 5 7 11 101
I wrote some code to find prime numbers up to a given number. Could you guys let me know ways to make my code more efficient or better? Or give insight on how I did? In addition, there is a problem in my code where certain numbers repeats twice or three times in a pattern. How do I fix this?
public class PrimeNumber2 {
public static void main(String[] args)
{
int max_prime = 10000;
for(int i = 3; i < max_prime; i+=2)
{
for(int j = 1; j < Math.sqrt(i); j++)
{
if(i % j == 0)
{
System.out.println(i);
}
}
}
}
}
Have a look at:
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
This is quite a nice way of doing it.
Here is some code for you to look at:
public void runEratosthenesSieve(int upperBound) {
int upperBoundSquareRoot = (int) Math.sqrt(upperBound);
boolean[] isComposite = new boolean[upperBound + 1];
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) {
System.out.print(m + " ");
for (int k = m * m; k <= upperBound; k += m)
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) {
if (!isComposite[m]) {
System.out.print(m + " ");
}
}
Here´s a tuned version of yours.
I did put the check if the number is prime into a seperate method. That´s also a part of the reason why your version did print values multiple times, since if it found out that it has a divisor, then it would print the values. (Also you´r algorythm would print basicly everything despite it beeing prime or not, for example it prints 15 and 27).
The reason why it did print multiple values was, that once you found a divisor it would have printed i, but it would continue looping. If it would have found another divisor, it would print i again(you can notice that it does not only print prime numbers).
Here is the fixed version of your´s
public static void main(String[] args) {
if(isPrime(2)) {
System.out.println(2);
}
int max_prime = 10000;
for(int i = 3; i < max_prime; i+=2)
{
if(isPrime(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int n) {
if(n<=1) return false;
if(n == 2) return true;
for(int i = 2;i*i<=n;++i) {
if(n%i == 0) return false;
}
return true;
}
Try this.
public class PrimeNumber2 {
public static void main(String[] args)
{
int max_prime = 10000;
System.out.println(2);
L: for (int i = 3; i < max_prime; i += 2)
{
for (int j = 3, max = (int)Math.sqrt(i); j <= max ; j += 2)
{
if(i % j == 0)
{
continue L;
}
}
System.out.println(i);
}
}
}
Here a way using parallelStream
System.out.println(2);
IntStream.range(1, 10000000)
.map(i -> i * 2 + 1)
.filter(i -> (i & 1) != 0 && IntStream.range(1, (int) (Math.sqrt(i)-1)/2)
.map(j -> j * 2 + 1)
.noneMatching(j -> i % j == 0)
.forEach(System.out::println);
Note: the ranges test the n-th odd number.
public static void main(String[] args) {
int upperBound = 30;
List<Integer> primes = new ArrayList<>();
// loop through the numbers one by one
for (int number = 2; number < upperBound; number++) {
boolean isPrimeNumber = true;
// check to see if the number is prime
for (int j = 2; j < number; j++) {
if (number % j == 0) {
isPrimeNumber = false;
break; // exit the inner for loop
}
}
// print the number if prime
if (isPrimeNumber) {
primes.add(number);
}
}
System.out.println("The number of prime is: " + primes.size() + ", and they are: " + primes.toString());
}
possible to dupplicate
get prime numbers and total prime numbers in range
public boolean isPrimeNumber(int number) {
for (int i=2; i<=number/2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
I am new here. I am trying to solve this exercise Problem 18 just for reinforcing my solving skills. I've already coded the answer. The task asks for "How many of the primes below 1,000,000 have the sum of their digits equal to the number of days in a fortnight?" (a fortnight is 14 days). My answers is 16708, but it is wrong. I hope you can help me. I don't know what my error is. I have 2 methods, 1 for generating the primes, and another for counting the digits of each prime.
This is my code:
import java.util.ArrayList;
import java.util.List;
public class Problema18 {
public static void main(String args[]) {
ArrayList<Integer> num = primes();
System.out.println(num);
count(primes());
}
public static ArrayList<Integer> primes() {
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= 1000000; i += 2) {
boolean isPrime = true;
int stoppingPoint = (int) (Math.pow(i, 0.5) + 1);
for (int p : primes) {
if (i % p == 0) {
isPrime = false;
break;
}
if (p > stoppingPoint) { break; }
}
if (isPrime) { primes.add(i); }
}
// System.out.println(primes);
return (ArrayList<Integer>) primes;
//System.out.println(primes.size());
}
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
if (sum == 14) { count++; }
}
System.out.println(sum);
}
System.out.println(count);
}
}
You should check whether sum == 14 outside the inner for loop. What happens now is that you also count those primes for which the sum of digits is larger than 14 but the sum of the digits in some prefix of the prime is equal to 14.
This part...
if (sum == 14) {
count++;
}
should be outside the inner for-loop - i.e. you want to do it each time you pass through the i for-loop, but not each time you pass through the j for-loop.
Like this:
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
}
System.out.println(sum);
if (sum == 14) {
count++;
}
}
System.out.println(count);
}