Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and
7 are twin primes, and 11 and 13 are twin primes. Write a Java program TwinPrimes.java that prompts
the user to input the search range of twin primes, display all the twin primes (2 pairs per line) within
the range, and print the number of twin primes found. The search range is assumed to be positive and
your program should repeatedly perform the same task until a sentinel value of -1 is entered.
The expected output of your program should be as follows:
Round 1:
Enter the search range: 100
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
Number of twin primes less than or equal to 100 is 8
Round 2:
Enter the search range: 150
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
......(Omitted)
Number of twin primes less than or equal to 200 is 15
Round 4:
Enter the search range: -1
End
I know that I am not complected the code, but I am struggling on how to print the Prime numbers in ( , ) ( , )way and how to calculate the number of twin primes show it at the end.
The below coding is what I had to do:
import java.util.Scanner;
import java.util.Random;
public class TwinPrimes {
public static void main(String[] args) {
int i = 0;
int A, B = 0, D = 0;
int num = 0;
System.out.println("Round" + " " + ++i + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
A = scn.nextInt();
{
if (A < 0)
System.out.println("End");
}
for (i = 3; i <= A; i++) {
int counter = 0;
for (num = B; num >= 1; num--) {
{
if (B % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
}
}
System.out.println("(" + i + "," + i + ")" + " " + "(" + i + "," + i + ")");
// sum Number of twin primes to
System.out.println("Number of twin primes less than or equal to " + A + " " + "is" + " ");
return;
}
}
}
package array1;
import java.io.IOException;
import java.util.Scanner;
public class Mainclass {
public static void main(String args[]) throws NumberFormatException, IOException
{
int a,k=0,line=0,count=0;
while(true)
{
System.out.println("Round" + " " + ++k + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
a= scn.nextInt();
{
if (a< 0)
{
System.out.println("End");
System.exit(0);
}
}
System.out.println("The Twin Prime Numbers within the given range are : ");
for(int i=2; i<=(a-2); i++)
{
if(isPrime(i) == true && isPrime(i+2) == true)
{
System.out.print("("+i+","+(i+2)+") ");
line++;
if(line==2)
{
System.out.println();
line=0;
}
count++;
}
}
System.out.println();
System.out.println("the number of twin prime numbers less than or equal to"+a+"is"+count);
}
}
static boolean isPrime(int n) //funton for checking prime
{
int count=0;
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
}
I am struggling on how to print the Prime numbers in ( , ) ( , ) way
You may use String.format. See How to use String.format in Java?
For example, String.format("Found pair (%d,%d)", prime1, prime2);
How to calculate the number of twin primes show it at the end.
Simply keep a counter, say int counter when you're looking for the prime pairs.
import java.util.Scanner;
public class Main {
// Consider writing a helper function to check primality
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int max_number = 100;
int counter = 0; // keep a count
for (int i = 2; i+2 < max_number; i++) {
if (isPrime(i) && isPrime(i+2)) {
counter++; // increment counter
String msg = String.format("Found pair (%d,%d)", i, i+2);
System.out.println(msg);
}
}
System.out.println("Total number of pairs is " + counter);
// Total number of pairs is 8
}
}
Related
It counts up to 5 and sum of 5 even numbers. I did it but it didn't work correctly(Mistake is about calculating the sum).Can you look at it ?
Here the code:
package com.java.ornekler;
public class Main {
public static void main(String[] args) {
int n = 1;
int count = 0;
int sum = 0;
do {
isEven(n);
if (!isEven(n)) {
n++;
continue;
} else {
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
}
while (n <= 10);
}
public static boolean isEven(int n) {
if ((n % 2) == 0) {
return true;
} else {
return false;
}
}
}
Output is:
2 is a even number
4 is a even number
6 is a even number
8 is a even number
10 is a even number
Sum is : 35
n++;
sum = sum + n; // here you incremented n then added to sum.
change to
sum = sum + n;
n++;
The reason why your sum is at 35 is because you increment your n one more time before you sum it together. Your total is 30 + numberOfN = 35
Your else statement should look like this
else {
System.out.println(+n + " is a even number ");
sum = sum + n;
n++; // this was above and should be here
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
When you find an odd number, you do this:
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
So, if n==4, first you bump it up so that n==5. Then you add it to sum, so sum increases by 5, not 4.
So fix this, add to sum before incrementing n.
More generally, instead of jumping up in ones, testing for even-ness, why not start on an even number, and jump up in twos?
And, rather than having a println and a break in an if within the loop, make it an exit condition of the loop, and put the println after the loop.
Along with comments above and you have duplicity statement: n++;.
Put that statement after if{}else{} block.
Revise the code as follows:
do {
isEven(n);
if (!isEven(n)) {
continue;
} else {
System.out.println(+n + " is a even number ");
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
n++;
}
while (n <= 10);
Java 8 syntax might be easier to follow using predefined functions for summing and limiting
package test.test;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Snippet {
public static void main(String args[]) {
int sum = IntStream.iterate(1, i -> i + 1).limit(10).filter(isEven()).peek(Snippet::printEvenNumber).sum();
System.out.println("Sum is : " + sum);
}
private static void printEvenNumber(int i) {
System.out.println(i + " is an even number");
}
private static IntPredicate isEven() {
return i -> i % 2 == 0;
}
}
I'm trying to program the Luhn Algorithm within Java.
My current code is :
import java.util.Scanner;
public class luhnAlgorithm {
public static void main(String[] args) {
System.out.println("main() : Entry Point");
Scanner input = new Scanner(System.in);
long num;
int digit;
int sum = 0;
System.out.println("Enter the digits of a credit card number : ");
num = input.nextLong();
while (num > 0) {
digit = (int) num % 10;
num = num / 10;
if (num % 2 != 0 ) {
digit *= 2;
}
if (digit > 9) {
digit -= 9;
}
sum += digit;
}
if(sum % 10 == 0) {
System.out.println("Credit card number is valid.");
}
else
System.out.println("Credit card number is invalid. Please try again.");
System.out.println("main() : Exit Point");
}
}
The problem I'm having is that when I enter in a valid credit card number, for example : 4012888888881881 (via PayPal Test Credit Card Accounts), it says it's invalid. But when I put in my own debit card number it says it's valid.
I know there's some code messed up in here, I just can't figure out what.
Any help would be appreciated and thanks in advance!
I think that I know where the problem is. You do the multiplication in a wrong way:
if (num % 2 != 0 ) {
digit *= 2;
}
You multiply digit when num is odd and in Luhn's algorithm you should multiply digit when this digit is on the even place in number moving from right to the left. Try to think about adding some index which will help you to know if a digit is on even place or not.
You can think about splitting your integer to array and then check if index of array is even or add to your while loop some index.
Carefully study this https://en.wikipedia.org/wiki/Luhn_algorithm
for example if you have 68 then you have: first iteration: digit = 8, num = 6 and sum =8 second iteration: digit = 6, num = 0 here you should multiply your digit by 2, because it is on the even place in number, but you don't do that and sum = 14 instead of 20
Okay I actually figured it out :).
import java.util.Scanner;
/*
* Author : Jonathan Patterson
* Date : 10/28/15
* Program : Luhn Algorithm; validates credit card numbers
*/
public class luhnAlgorithm {
public static void main(String[] args) {
System.out.println("main() : Entry Point");
Scanner input = new Scanner(System.in);
long num;
double digit = 0;
int sum = 0;
int n = 1;
int i = 0;
System.out.println("Enter the digits of a credit card number : ");
num = input.nextLong();
while (num > 0) {
digit = num % 10;
num = num / 10;
System.out.println(n + " digit is : " + digit);
if (i % 2 != 0 ) {
digit *= 2;
}
System.out.println(n + " digit is : " + digit);
if (digit > 9) {
digit = (digit % 10) + 1;
}
else
digit *= 1;
System.out.println(n + " digit is : " + digit);
sum += digit;
n++;
i++;
}
System.out.println("Sum of the digits is : " +sum);
if(sum % 10 == 0) {
System.out.println("Credit card number is valid.");
}
else
System.out.println("Credit card number is invalid. Please try again.");
System.out.println("main() : Exit Point");
}
}
Adding an additional answer to this in case anyone else finds this post.
There is a bitbucket project with a valid implementation:
https://bitbucket.org/javapda/npi-validator/src/master/
This if for verifying NPI provider numbers which is an implementation of the Luhn algorithm.
package org.bitbucket.javapda.npi;
import java.util.ArrayList;
import java.util.List;
public class NpiValidator {
private String npi;
public NpiValidator(String npi) {
this.npi = npi.trim();
}
public boolean isValid() {
return npi.length() == 10 && complies();
}
private boolean complies() {
if (!npi.matches("[0-9]{10}")) {
return false;
}
Character lastDigit = npi.charAt(9);
List<Integer> everyOther = listWithEveryOtherDoubled(npi.substring(0, 9));
int sum = 0;
for (Integer num : everyOther) {
sum += sumOfDigits(num);
}
int total = sum + 24; // 24 to account for 80840
int units = total % 10;
int checkDigit = (units != 0) ? (10 - units) : units;
return (Character.getNumericValue(lastDigit) == checkDigit);
}
private List<Integer> listWithEveryOtherDoubled(String str) {
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
nums.add(2 * Character.getNumericValue(str.charAt(i)));
} else {
nums.add(Character.getNumericValue(str.charAt(i)));
}
}
return nums;
}
private static int sumOfDigits(int number) {
int num = number;
int sum = 0;
while (num > 0) {
sum += (num % 10);
num = num / 10;
}
return sum;
}
public static void main(String[] args) {
System.out.println("Hello, World!");
// System.out.println(sumOfDigits(16));
System.out.println("1234567890".matches("[0-9]{10}"));
System.out.println("123456789".matches("[0-9]{10}"));
}
}
Here's my code so far:
public class EvenOdd
{
public static void main(String[]args)
{
System.out.print("Even numbers between 50 and 100: ");
int e = 50;
while (e <= 100) {
System.out.print(" " + e);
e += 2;
}
System.out.print("\nOdd numbers between 50 and 100: ");
int i = 51;
while (i <= 100) {
System.out.print(" " + i);
i += 2;
}
}
}
How can I reduce these two while loops to just one while loop?
Store the numbers in two StringBuilders, one for the odd numbers and the other for the even numbers :
public class EvenOdd
{
public static void main(String[]args)
{
StringBuilder even = new StringBuilder();
StringBuilder odd = new StringBuilder();
int e = 50;
while (e <= 100) {
if (e%2 == 0)
even.append (" " + e);
else
odd.append (" " + e);
e++;
}
System.out.print("Even numbers between 50 and 100: " + even.toString());
System.out.print("\nOdd numbers between 50 and 100: " + odd.toString());
}
}
public static void main(String[]args)
{
StringBuilder evenString = new StringBuilder("Even numbers between 50 and 100: ");
StringBuilder oddString = new StringBuilder("Odd numbers between 50 and 100: ");
int e = 50;
while (e <= 100) {
if((e % 2) == 0)
{
evenString.append(" " + e);
}
else
{
oddString.append(" " + e);
}
e++;
}
System.out.println(evenString);
System.out.println(oddString);
}
Use a two StringBuilders to store the strings you want to display then write them out after your done looping. Each loop do modular division (%) to see if its even or odd. If the remainder is 0 then it's even if it's not then it's odd. Based on which one it is just append it to the appropriate StringBuilder.
Reducing code duplication is often a good thing. The most basic tool that Java provides are methods, so you could extract the behavior of your loop in a method and write an equivalent program:
public class EvenOdd
{
public static void main(String[]args)
{
System.out.print("Even numbers between 50 and 100: ");
printEverySecondNumber(50, 100);
System.out.print("\nOdd numbers between 50 and 100: ");
printEverySecondNumber(51, 100);
}
public static void printEverySecondNumber(int start, int end){
int current = start;
while (current <= end) {
System.out.print(" " + current);
current += 2;
}
}
}
Note that this program behaves just the same: The loop will stil get executed twice, but it is not duplicated in code.
Use lists. They print out nicely.
public class EvenOdd
{
public static void main(String[]args)
{
List<String> even = new ArrayList<String>();
List<String> odd = new ArrayList<String>();
int e = 50;
while (e <= 100) {
if (e%2 == 0)
even.add(String.valueOf(e));
else
odd.add(String.valueOf(e));
e++;
}
System.out.print("Even numbers between 50 and 100: " + even);
System.out.print("\nOdd numbers between 50 and 100: " + odd);
}
}
Here is a solution without storing numbers
public static void main(String[] args) {
int i = 0;
System.out.print("Even numbers between 50 and 100: ");
while (i <= 50) {
if (i == 26) {
System.out.print("\nOdd numbers between 50 and 100: ");
}
if (i <= 25) {
System.out.print (" " + (2 * i + 50));
} else {
System.out.print (" " + (2 * (i - 25) + 49));
}
i++;
}
}
If you are determined to do a single loop
int n = 50;
System.out.print("Even numbers between 50 and 100:");
while(n < 151){
if(n <= 100)
System.out.print(" " + n);
else
System.out.print(" " + (n-50));
if(n != 100)
n = n + 2;
else{
System.out.print("\nOdd numbers between 50 and 100:");
n = n + 1;
}
}
The benefit to this is you aren't building any unnecessary objects or having to manage anything other than n really.
If your goal is to reduce loop iterations
StringBuilder evenString = new StringBuilder();
StringBuilder oddString = new StringBuilder();
int n = 50;
while(n <= 100){
evenString.append(" " + n);
if(n != 100)
oddString = oddString.append(" " + (n + 1));
n = n + 2;
}
System.out.println("Even numbers between 50 and 100:" + evenString);
System.out.print("Odd numbers between 50 and 100:" + oddString);
Something to notice, this cuts your iterations in half over using a single while with if statements.
Just re-start iterations by re-setting the counter:
public class EvenOdd
{
public static void main(String[]args)
{
int e = 0;
while (1) {
if (e==0) {
System.out.print("Even numbers between 50 and 100:");
e = 50;
}
else
if (e==102) {
System.out.print("\nOdd numbers between 50 and 100:");
e = 51;
}
else
if (e==101) {
System.out.print("\n");
break;
}
System.out.print(" " + e);
e += 2;
}
}
}
I am printing the factorial of the first 10 numbers, so it is 0 - 9. The below code works for me. But I am unable to make the loop such that the factorial of 0 is within the loop too. Any advice is appreciated. Thank you.
public class fact {
public static void main(String[] args) {
System.out.println("\n\n(f) Loop to print first 10 factorial numbers");
System.out.println("\nFactorial of 0 is 1");
int fact = 1;
int index = 1;
while (index < 10)
{
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
index++;
}
}
}
How about adding an if condition in your while loop for index 0
int fact = 1;
int index = 0;
while (index < 10)
{
if(index == 0)
System.out.println("\nFactorial of 0 is 1");
else {
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
}
index++;
}
The factorial of 0 is a special case, so you are better off printing it outside the loop, just as you are doing now.
For big n numbers find factorial and its digit count .
import java.util.Scanner;
public class N_Faktorial {
public static void main(String [] args)
{
int u=1,A[]=new int[9999999];
Scanner scan =new Scanner(System.in);
System.out.print("n=");
int n=scan.nextInt();
A[1]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++) {
A[j]*=i;
}
for(int j=1;j<=n;j++)
{
if(A[j]>9)
{
A[j+1]+=A[j]/10;
A[j]%=10;
}
if(A[u+1]!=0) {
u++;
}
}
}
System.out.print(n+"! digit count:"+u+"\\n Result: \\n");
for(int i=u;i>=1;i--)
{
System.out.print(A[i]);
}
}
}
factorialList(10);
public static int factorialList(int indexMax) {
int fact = 1;
if (indexMax > 0) fact = indexMax * factorialList(indexMax - 1);
System.out.println("Factorial of " + indexMax + " is " + fact);
return fact;
}
Fn calls are less effective than loops but I bet it would be optimized to ~ the same on task of this size.
You can do like this
int fact = 1;
int index = 0;
while (index < 10)
{
fact=(index==0)?1:fact*(index);
System.out.println("Factorial of " + index + " is " + fact);
index++;
}
i wrote a program to display fibonacci series in java but now i want the numbers in the sequence to be displayed in tens that is the first ten fibonacci numbers on one line followed by the next ten on the next line and so.....
i have been having real problems making that possible.
this is the program:
import java.util.Scanner;
import java.math.BigInteger;
class Fibonacci {
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
int number = new Scanner(System.in).nextInt();
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
for (int i = 1; i <= number; i++) {
System.out.println(fibonacciLoop(i) + " ");
}
}
public static BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}
print (don't println) each number to have them on the same line. And whenever your counter i is a multiple of 10, start a new line.
for (int i = 1; i <= number; i++) {
System.out.print(fibonacciLoop(i) + " ");
if (i % 10 == 0)
System.out.println();
}
if(i % 10 == 0)
{
System.out.println();
}
Or if you wanted to be fancy.
System.out.print(fibonacciLoop(i) + " " + (i % 10 == 0? "\n":""));
Note that your fibonaci calculation does not work due to the following for loop:
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
The follow will do what you requested:
import java.math.BigInteger;
import java.util.Scanner;
import java.util.LinkedList;
public class Test {
Test(int number) {
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
LinkedList<BigInteger> list = new LinkedList<BigInteger>();
for (int i = 1; i <= number; i++) {
list.add(fibonacciLoop(i));
if(list.size() == 10) {
printFibo(list);
list = new LinkedList<BigInteger>();
}
}
if(!list.isEmpty()) printFibo(list);
}
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
new Test(new Scanner(System.in).nextInt());
}
private void printFibo(LinkedList<BigInteger> list) {
for(BigInteger fiboNumber : list) {
System.out.print(fiboNumber + " ");
}
System.out.println("");
}
public BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}