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;
}
}
Related
In short, again I found the task on internet:
Input integers from the keyboard, check whether prime numbers or not. When you input 0, the program ends.
So far, I wrote the logic for checking the integer if it's prime or not. The main stumbling block was that I should read several integers from one string and stop program if last integer is 0. So when I tried to add a loop to iterate over the input and check whether the integer is prime or not, my logic doesn't work and it returns only 1 st integer without others.
import java.util.Scanner;
public
class PrimeNumber
{
public
static void main(String[] args)
{
int temp;
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] arr = new int[num];
for (int i = 0; i < arr.length; i++)
{
arr[i] = sc.nextInt();
for (int y = 2; y <= num / 2; i++)
{
temp = num % i;
if (temp == 0)
{
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
I recommend if you can check this link: Check if an int is prime Java
Write a boolean function that checks an integer if it is prime or not. You do not need to create a O N^2 algorithm from input box.
Step 1: Check one integer and see if returns true( means it is prime )
Step 2: Try random numbers and see if they work as well.
Step 3: Add an array and see if contents of the array has prime numbers or not. Then you can print out any message you like.
See this example from the same reference to get started.
https://onecompiler.com/java/3y2cxy9ea
Your thought process was good.
The snippet with the if-else statement is outside of the for loop, so it will only happen once.
The value of num is just the number of int values the user will type in (basically arr.length). It should instead be checking primality of arr[i]. If arr[i] is divisible by some number other than 1 or arr[i], it is not prime. Also, if arr[i] is not greater than 1, it is not prime, either.
Lastly, make sure isPrime gets reset to true.
I recommend adding instructions in the form of print(), so it becomes clearer which number is which:
public static void main(String[] args)
{
int temp;
boolean isPrime;
Scanner sc = new Scanner(System.in);
System.out.print("Number of integer values: ");
int numberOfInts = sc.nextInt();
int[] arr = new int[numberOfInts];
for (int i = 0; i < numberOfInts; i++)
{
isPrime = true;
System.out.print("Int " + (i+1) + " = ");
arr[i] = sc.nextInt();
for (int y = 2; y <= arr[i] - 1; y++)
{
temp = arr[i] % y;
if (temp == 0)
{
isPrime = false;
break;
}
}
if (arr[i] <= 1) {
isPrime = false;
}
if (isPrime)
System.out.println(arr[i] + " is a Prime Number");
else
System.out.println(arr[i] + " is not a Prime Number");
}
}
As for exiting the program, put this at the start of the enclosing for loop:
if (arr[i] == 0) {
break;
}
There are better solutions than this, but on a basic level, this is fine.
You can try using this function to check that the number is prime:
private static boolean isPrime(int number) {
return java.math.BigInteger.valueOf(number).isProbablePrime((int) Math.log(number));
}
Then you can iterate through the array and check each of its elements with this function
My version of this program:
public class Main {
public static void main(String[] args) {
try(java.util.Scanner sc = new java.util.Scanner(System.in)) { //use try-with-resources block to avoid resources leak
//filling an array
int[] ints = new int[sc.nextInt()];
//if program gets 0, it stops filling
for(int i = 0; i < ints.length; i++) {
int temp = sc.nextInt();
if(temp == 0) break;
ints[i] = temp;
}
//check
for(int i = 0; i < ints.length; i++)
if(ints[i] != 0) System.out.printf("%s is%s a prime number.\n", ints[i], isPrime(ints[i]) ? "" : "n't");
}
}
private static boolean isPrime(int number) { //Some maths
return java.math.BigInteger.valueOf(number).isProbablePrime((int) Math.log(number));
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am using the below code and it's giving me the option to enter the final value but I need to give input of two values and also the total count of prime numbers between that range.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter two positive integers: ");
int input = scanner.nextInt();
List<Integer> primes = new ArrayList<>();
// loop through the numbers one by one
for (int i = 2; i < input; i++) {
boolean isPrimeNumber = true;
// check to see if the number is prime
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrimeNumber = false;
break; // exit the inner for loop
}
}
// print the number if prime
if (isPrimeNumber) {
primes.add(i);
}
}
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes.toString());
}
Your but fine but not exactly as you've described.
scanner.nextInt() - can produce only one int value (or causes InputMismatchException if input isn't an int).
You said 'i need to give input of two values' - to accomplish it you may have to read these values separately using nextInt() or you can read both as a line, then split the line, and parse to int separately.
The first option is definitely easier.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter two positive integers: ");
System.out.print("start = ");
int start = scanner.nextInt();
System.out.print("end = ");
int end = scanner.nextInt();
List<Integer> primes = new ArrayList<>();
// loop through the numbers from start to end inclusive
for (int i = start; i <= end; i++) {
// check if i is prime
if (isPrime(i)) {
primes.add(i);
}
}
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes);
}
private static boolean isPrime(int i) {
boolean isPrime = true;
// check to see if the number is prime
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break; // exit the inner for loop
}
}
return i != 1 && isPrime;
}
Let us know, please, is that what you wanted to achieve?
MORE PERFORMANT IMPLEMENTATION
In this implementation, all functionality for finding primes resides in the separate class PrimeUtil.
The constructor of this class is private and to create an instance of this class, it provides a static method getInstance() which accepts two integer numbers representing the desired range.
This is done in order to initialize the object by invoking the init() method and return a fully-fledged object primeUtil, containing the result to the caller.
Method init() populates primes list. All discovered prime numbers will be added to it.
primes list acts as cash. There's no need to rediscover primes over and over again like it's dome in the first solution. That drastically improves the performance.
Another optimization is the way to determine the next probable prime implemented in the method getNextCandidate().
The mathematical logic behind this method is based on the fact that all numbers, that are evenly divisible by 2 and 3 are already eliminated because 2 and 3, are added to the primes list by default and there is no need to consider any number that is divisible 2 or 3. From this fact we can make a conclusion that the remainder of division by 6 for every potential prime cant be equal: 0; 2; 3; 4. I.e. valid prime must fulfill the condition prime % 6 == 1 || prime % 6 == 5.
main
public static void main(String[] args) {
printPrimes();
}
public static void printPrimes() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter two positive integers: ");
System.out.print("start = ");
int start = scanner.nextInt();
System.out.print("end = ");
int end = scanner.nextInt();
List<Integer> primes = PrimeUtil.getInstance(start, end).getResult();
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes);
}
PrimeUtil class
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.*;
import static java.util.stream.Collectors.toUnmodifiableList;
public class PrimeUtil {
private final List<Integer> primes;
private final int loBound;
private final int hiBound;
private PrimeUtil(int loBound, int hiBound) {
this.primes = new ArrayList<>();
this.loBound = loBound;
this.hiBound = hiBound;
}
public static PrimeUtil getInstance(int loBound, int hiBound) {
PrimeUtil primeUtil = new PrimeUtil(max(loBound, 2), hiBound);
primeUtil.init();
return primeUtil;
}
private void init() {
if (loBound <= 2) primes.add(2);
if (loBound <= 3) primes.add(3);
int candidate = 5;
while (candidate <= hiBound) {
if (isPrime(candidate)) {
primes.add(candidate);
}
candidate = getNextCandidate(candidate);
}
}
private boolean isPrime(int candidate) {
boolean isPrime = true;
for (int i = 0; i < primes.size() && primes.get(i) <= sqrt(candidate); i++) {
if (candidate % primes.get(i) == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
private int getNextCandidate(int candidate) {
return candidate % 6 == 5 ? candidate + 2 : candidate + 4;
}
public List<Integer> getResult() {
return primes.stream()
.dropWhile(i -> i < loBound)
.collect(toUnmodifiableList());
}
}
All you need is to ask the user for two integer numbers using Scanner two times.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter two positive integers:");
System.out.print("low range: ");
int lo = scan.nextInt();
System.out.print("high range: ");
int hi = scan.nextInt();
List<Integer> primes = getPrimeNumbers(lo, hi);
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes);
}
private static List<Integer> getPrimeNumbers(int lo, int hi) {
List<Integer> primes = new ArrayList<>();
for (int i = lo; i <= hi; i++)
if (isPrime(i))
primes.add(i);
return primes;
}
private static boolean isPrime(int val) {
if (val == 1)
return false;
if (val == 2 || val == 3)
return true;
for (int i = 2, sqrt = (int)Math.sqrt(val); i <= sqrt; i++)
if (val % i == 0)
return false;
return true;
}
use two Scanners to get second input
you can remove the list and adding elements to it and use a counter if you want only the number of prime numbers :)
So the solution would be :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the first positive integer: ");
int firstNumber = scanner.nextInt();
System.out.println("Please enter the second positive integer: ");
// you should have another scanner hence an other text output to invite user
int secondNumber = scanner.nextInt();
List<Integer> primes = new ArrayList<>(); // we do not really need this if we want only the number of prime number and not the list but i'll use it for you anyway
for(int i = firstNumber; i <= secondNumber; i++) //the use the input variables
{
if (isPrime(i)){ // we made a function here to make things clear. it's role to tell weather a number is a prime or not
primes.add(i); // we add prime numbers to this list as you used a list. You can go for an easier solution just a counter++ each time ;)
}
}
System.out.println("The number of prime numbers in this range is: " + primes.size());
}
static boolean isPrime(int num){
if (num <= 1)
return false;
for(int i = 2; i * i <= num; i++)
// If a divisor of n exists
if (num % i == 0)
return false;
return true;
}
A prime number is a positive integer greater than 1 that is divisible only by itself and 1. In this assignment you are responsible to write a complete Java program to display first N prime numbers. In other words, your program should list the first N prime numbers.
Functional Requirements
Your program should prompt the user for a positive number, or a value of -1 to terminate the program. If the user enters 0, or a negative number, the program will also end immediately.
Your program will display the first N prime numbers given by the user. For example, if the user enters 3, the program should display: “2, 3, 5” which are the first three prime numbers. If the user enters 6, the output would be: “2, 3, 5, 7, 11, 13”.
Sample Run
Welcome to the list of N prime numbers program!
===============================================
Please enter the value of N (positive integer):
6
First 6 prime numbers are:
2
3
5
7
11
13
When i worked on it i got this but need help finishing
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int n;
int status=1;
int num=3;
n = scan.nextInt();
if(n>=1) {
System.out.println(2);
for(int count=2; count<=n; count++) {
for(int j=2; j<=Math.sqrt(num);j++) {
if(num%j==0) {
status =0;
break;
}
if(status!=0) {
System.out.println(num);
count++;
}
}
status=1;
num++;
}
}
}
}
you should give a out.println("enter the number of prime numbers needed");
then read it using scanner(for example if it is reading into x) and provide a if condition as
if(x<=0)
{
break;
}
and balance code can be given in the else condition.
public class prime {
public static boolean isPrime(int n) {
for(int j=2; j<=Math.sqrt(n)+1;j++) { //Math.sqrt(n) + 1 because you want to check more than half of the original value.
if(n%j==0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int inputNum; //try making the variable name meaningful
inputNum = scan.nextInt();
int count = 0;
int startingVal = 2;
while(count<inputNum) {
if(inputNum==-1) {
break;
}
if(count==0) {
System.out.println(2);
count++;
}
else if(isPrime(startingVal)) {
System.out.println(startingVal);
count++;
}
startingVal ++;
}
}
}
This should work fine. As #Amadan in the comment section already mentioned, your program did not work because your if(status!=0) is in the for loop.
Also, setting the variable names meaningful helps you fix or edit your code easier.
please use below method to get prime no.
static List<Integer> nthPrimeNo(int nth){
List<Integer> integers = new ArrayList<>();
int num, count, i;
num=2;
count=0;
for (int j = 0; j < nth; j++) {
while (count < j){
num=num+1;
for (i = 2; i <= num; i++){
if (num % i == 0) {
break;
}
}
if ( i == num){
count = count+1;
}
}
integers.add(num);
}
return integers;
}
Or do you want to get 10 greater than primes number,
static List<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
List<Integer> primeNumbers = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
use this function call System.exit(0); in exit condition
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).
So i have this problem where when i factor a number, lets say 15, i have to display this: 15=3x5 but instead what i get is 3x5x5 and i have no clue of how to make it that so it only displays 3x5. And then another problem i have is to find whether the number i inputted is a prime number or not. Any way of fixing this? I just need that and the other stuff im gonna edit after that.
public class PrimeFactor
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int a;
int d;
int remainder=0;
int count=2;
int c=0;
String s;
System.out.println("Enter an integer to be factored:");
a=input.nextInt();
s="";
d=a;
while(a>1)
{
if(a>1)
{
s="";
while(a>1)
{
remainder=a%count;
if (!(remainder>0))
while(remainder==0)
{
remainder=a%count;
if (remainder==0)
{
a=a/count;
c=c+1;
s=s+count+"x";
if (a==1)
s=s+count;
}
else
count++;
}
else
count++;
}
if (a%count==0)
{
System.out.println(d +"=" + s);
System.out.println(d+" is a prime number.");
}
else
System.out.println(d +"=" + s);
}
// TODO code application logic here
}
}
}
This determines if the number is prime or not the quickest way. Another method would be to use a for loop to determine the number of factors for the number and then say it's prime if it has more than two factors.
int num; // is the number being tested for if it's prime.
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) // only have to test until the square root of the number
{
if (num%i == 0) // if the number is divisible by anything from 2 - the square root of the number
{
isPrime = false; // it is not prime
break; // break out of the loop because it's not prime and no more testing needed
}
}
if (isPrime)
{
System.out.println(num + " is a prime number.");
}
else
{
System.out.println(num + " is a composite number.");
}
You are not constructing the factorization string quite right:
When you find that 3 divides a=15 you set s to 3x and set a to the quotient, so a=5
When you find that 5 divides a=5 you append 5x to s, so now s is 3x5x. Then you set a to the quotient, which is 1. Since the quotient is now 1, you append 5 again, so now you get 3x5x5.
What you'll want to do is append only 5 when a=1, not 5x5. You have to change this:
s=s+count+"x";
if (a==1)
s=s+count;
to this:
if (a==1) {
s=s+count;
} else {
s=s+count+"x";
}
How about trying like this:-
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("Number is a prime");
else
System.out.println("Number is not a prime");
break;
}
}
These are quite straight-forward methods you can use to factor a number and determine if it is a prime number:
public static int oneFactor(int i) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
return j;
}
return -1;
}
public static Integer[] primeFactors(int i) {
List<Integer> factors = new ArrayList<Integer>();
boolean cont = true;
while (cont) {
int f = oneFactor(i);
if (i > 1 && f != -1) {
i /= f;
factors.add(f);
} else
factors.add(i);
if (f == -1)
cont = false;
}
return factors.toArray(new Integer[factors.size()]);
}
public static boolean isPrime(int i) {
if (i == 2 || i == 3)
return true;
if (i < 2 || i % 2 == 0)
return false;
for (int j = 3, end = (int) Math.sqrt(i); j <= end; j += 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
I am sure one can use faster algorithms, but those would be at the cost of simplicity, and it doesn't seem like you need high speed methods.
They all operate on ints, but its easy to change them to work with longs.
If you have any questions, feel free to ask!
You want to write a loop which loops through numbers 1 to (Inputted Number). And if you found a factor, you print it and divide the input by the factor. (And test if it can be divided again by the same number), else then skip to the next number.
Keep doing this until your input divides down to 1.
This program will break the number down to prime factors:
public class Factor {
public static void main() {
//Declares Variables
int factor = 15;
int i = 2;
System.out.println("Listing Factors:\n");
while (factor>1) {
//Tests if 'i' is a factor of 'factor'
if (factor%i == 0) {
//Prints out and divides factor
System.out.println(i);
factor = factor/i;
} else {
//Skips to next Number
i++;
}
}
}
}
Output:
Listing Factors:
3
5