So I have this problem that was assigned to me where you have write a program that asks for a starting integer and an ending integer and returns the length of the longest hailstone sequence, the number between the start and the end where it occurs, and the actual sequence.
I figured out most of it, but I was stuck on printing out the actual largest sequence. If anyone could please help me on this, it would really help. Thank you!
import java.util.Scanner;
public class Hailstone
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int first, last, counter = -500, highestSequence = 0, highestNumber = 0, number = 0, sequence = 0;
System.out.println("First candidate?");
first = scan.nextInt();
System.out.println("Last candidate?");
last = scan.nextInt();
for(int x = first; x <= last; x++)
{
number = x;
counter = 1;
while(number !=1)
{
if(number % 2 == 0) //even
{
number = number/2;
}
else //odd
{
number = number*3 + 1;
}
counter++; //counts sequence
}
if(counter > highestSequence)
{
highestSequence = counter;
highestNumber = x;
sequence = number;
}
}
System.out.println("longest sequence of " + highestSequence + " occurs at " + highestNumber);
}
}
You can simply take your highestNumber and run the code that computes the sequence on it to print it. It will help if you extract the code to a separate method (just a sketch, verify it and modify it yourself):
public int checkSequence(int x, boolean print) {
int number = x;
while(number !=1)
{
if (print) {
System.out.print(number + " ");
}
if(number % 2 == 0) //even
{
number = number/2;
}
else //odd
{
number = number*3 + 1;
}
counter++; //counts sequence
}
return counter;
}
In your program you will then call checkSequence(x, false) and after you're done you'll call checkSequence(highestNumber, true).
Related
How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}
I'm having issues getting all prime numbers between a given integer A and integer B.
The issue is that the output goes well beyond whatever I defined for B. I thought that the
if (isPrime){
count++;
would fix this but the output still goes well beyond the intended number of integer B.
For example if int valueA = 1 and int valueB = 100, it'll get prime numbers from around 1 to 500 before stopping, instead of just ending the check at 100.
Thank you for any assistance.
import java.util.*;
public class PrimeNumbersTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// Ask user to input an integer value for A and B
System.out.print("Enter the value of A (must be an integer): ");
int valueA = input.nextInt();
System.out.print("Enter the value of B (must be an integer): ");
int valueB = input.nextInt();
System.out.println("The prime numbers between " + valueA + " and " + valueB + " are:");
final int LINE = 10;
int count = valueA;
int number = 2;
while (count < valueB) {
// Assume the number is prime
boolean isPrime = true;
// Test if number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
if (isPrime) {
count++;
if (count % LINE == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
number++;
}
}
}
When you want to work on a range of number, use a for loop instead of while loop to reduce confusion. You obviously want
for(int number = valueA; number <= valueB; number++){/*check if number is prime*/}
Example:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
if(isPrime(number))
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}
public static boolean isPrime(int n)
{
for(int i = 2; i*i <= n; i++)
{
if(n % i == 0)
{
return false;
}
}
return n > 1;
}
For your requirement of checking isPrime inline:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
boolean isPrime = number > 1;
for(int i = 2; i*i <= number; i++)
{
if(number % i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}
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
}
}
Only manual algorithms on variables are allowed. Collections like list, arrays etc. aren't to be used. (I Used .length() function in the program but it can be manually done by putting a space after every input and counting the number of chars till a space is found)
The problem that using arrays would solve is to store any number of values that the user inputs. This can be solved by storing the values in a string. Since we'd have to know how many characters to pick from the string to form a number, I've also stored the lengths of the numbers in a separate string(Length would generally be of only 1 digit so we'd know for sure that the length of nth number would be at the nth char in the lengthstorage string.)
The algorithm:
Take a number from the string and subtract it from every other number in the string.
If the result is positive, add 1 to the int 'pos'; if negative, to 'neg'; if zero, to 'copy'.
If odd number of numbers are inputed, then the number for which pos + copy >= n/2 and neg + copy >= n/2 is the median.
If even number of numbers are inputed, then we'd have 2 middle numbers fmedian and smedian whose average would be the median. (Refer the code for algorithm).
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input,inputstorage,lengthstorage,inputlength;
int nonrep=0;
System.out.println("Enter the number of values");
int n = sc.nextInt();
int fmedian=0,smedian=0;
System.out.println("Enter a value");
input= sc.next(); //String
inputlength = "" + (char)(input.length()+48);
inputstorage = input;
lengthstorage = inputlength;
for (int i=1; i<n; i++)
{
System.out.println("Enter a value");
input = sc.next();
inputstorage = inputstorage + input;
lengthstorage = lengthstorage + (char)(input.length()+48);
}
int mainnumpos = 0;
for(int j=0;j<n;j++)
{
int copy=0;
int mainnumlength = lengthstorage.charAt(j) - 48;
int neg=0,pos=0;
int mainnum = 0; int factor = 1;int mainnumsign = 0;
for (int m =mainnumlength-1; m >= 0; m--)
{
if(inputstorage.charAt(mainnumpos+m)=='-')
{
mainnumsign = 1;
}
else
{
mainnum += (inputstorage.charAt(mainnumpos+m) - '0') * factor;
factor *= 10;
}
}
mainnumpos = mainnumpos + mainnumlength;
if(mainnumsign==1)
{
mainnum = -mainnum;
}
int position = 0;
for (int q=0;q<n;q++)
{ int fnumsign = 0;
int fnumlength = lengthstorage.charAt(q) - 48;
int fnum = 0;
factor = 1;
for (int l =fnumlength-1; l >= 0; l--)
{
if(inputstorage.charAt(position+l)=='-')
{
fnumsign = 1;
}
else{
fnum += (inputstorage.charAt(position+l) - '0') * factor;
factor *= 10;
}
}
if(fnumsign==1)
{
fnum = -fnum;
}
if((mainnum-fnum)>0)
{
pos++;
}
else if((mainnum-fnum)<0)
{
neg++;
}
else{
copy++;
}
position = position + fnumlength;
}
if((n%2)!=0){
if((double)(pos+copy)>=((double)n)/2.0 && (double)(neg+copy)>=((double)n)/2.0)
{
if(nonrep==0)
{
System.out.println("The median is: "+ mainnum);
nonrep++;
}
}
}
else
{
if ((double)(pos+copy)==(double)n/2.0)
{
fmedian=mainnum;
}
else if((double)(neg+copy)==(double)n/2.0)
{
smedian = mainnum;
}
else if((double)(pos+copy)>=(double)n/2.0 && (double)(neg+copy)>=(double)n/2.0 )
{
fmedian = mainnum;
smedian = mainnum;
}
if(j==n-1){
double evenmedian = ((double)(smedian + fmedian))/2.0;
System.out.println("The median is: "+evenmedian);
}
}
}
}
}
I was coding on a program that would keep on accepting numbers until the user enters -1. Then it would display the number of items that are divisible by 9; using a special property- sum of digits of numbers that are divisible by 9, are themselves divisible by 9. I have been told to rely on a heavily modular approach. Simple input, no arrays.
There is no compilation errors and stuff, but the value of count is always wrong. For instance, if I input 18,18,4,4,2,5,19,36,-1, the expected output is 3, but the output comes out as 4. I have no clue why. I have tried count++ and ++count, they yield the same output. Where am I going wrong?
import java.util.Scanner;
public class Div{
static Scanner sc = new Scanner(System.in); boolean run = true; static int n = 0;
static int count = 0;
public static void main(String[] args){
Div a = new Div();
a.accept();
a.display();
}
void accept(){
while (run){
System.out.println("Enter the number");
n = sc.nextInt();
if (isDivisibleByNine(n)){
count = count + 1;
}
if (n == -1){
run = false;
}
}
}
static int sumOfDigits(int a){
int m = a; int sum = 0;
while (m>0){
sum = sum + (m%10); m /= 10;
}
return sum;
}
static boolean isDivisibleByNine(int x){
if (sumOfDigits(x)%9==0){
return true;
}
else {
return false;
}
}
void display(){
System.out.println("The total number of numbers that are divisible are: " + count);
}
}
The problem is with your end value -1. For -1 also your sumOfDigits function will return 0. so only count is incremented by 1 always.
while (run){
System.out.println("Enter the number");
n = sc.nextInt();
if (n == -1){
break; //Break if the end of input reached.
}
if (isDivisibleByNine(n)){
count = count + 1;
}
}
The final number that your program believes is divisible by 9 is your -1.
You go through the complete loop for it - your sum only goes while the number is above 0, so it terminates immediately and returns 0. 0 % 9 is 0, so it increments your counter then ends. Check for this by changing your loop:
if (n == -1){
run = false;
}
else if (isDivisibleByNine(n)){
count = count + 1;
}
You are not computing the sum of digits.
This is how you compute it :
static int sumOfDigits(int a){
int m = a; int sum = 0;
while (m>0){
sum = sum + (m%10);
m /= 10;
}
return sum;
}
EDIT (after your fix of sumOfDigits) :
You get the wrong count because you also check if -1 is divisible by 9, and it returns true, because sumOfDigits doesn't handle negative integers properly.
Here's an easy fix:
void accept(){
while (run){
System.out.println("Enter the number");
n = sc.nextInt();
if (n == -1){
run = false;
}
else if (isDivisibleByNine(n)){
count = count + 1;
}
}
}
change as this .
static boolean isDivisibleByNine(int x){
if(x>0){
if (sumOfDigits(x)%9==0){
return true;
}
else {
return false;
}
}else{
return false;
}
}