List of divisors of a number - java

it's my first post so DO stomp me if I wrote something stupid.
I've just started IT classes, and today on "while" loops class my tutor gave us the following homework:
Write a program which reads a natural number n and displays in one graphical box all its divisors from the interval [2; n-1].
So far I came up with a code that works but the result is a bit wrong:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[x] = x;
x = x + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(dvr));
}
}
The problem is that the loop fills the array with a lot of zeroes, and the screenshot of tutor's results shows a window listing only the divisors.
I tried to do this with ArrayList, but that's black magic for me right now and my tutor didn't teach us yet how to use anything beyond stuff used in my code anyway.
Any help highly appreciated.

The main problem you're having is that you're going to have an unknown number of values you want to print, but you're using an array to store them, and arrays have a fixed size. Since you have an array of int, it's going to be entirely populated with the default value of zero.
Ideally, you'd only print the first bunch of non-zero values of your array, but you're storing the divisors scattered throughout your array.
dvr[x] = x; stores each value at an index of that value, when really you should just store each new value into the next open spot in the array.
Create a separate index variable, and store each value using it instead:
int index = 0;
while (x >= 2 && x <= d) {
...
if (y == 0) {
dvr[index++] = x;
...
Then when your main loop is done, you can create a new "display array" that holds only the divisors, and not the zeros. At this point, index tells you exactly how large it needs to be:
int[] display = Arrays.copyOf(dvr, index);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(display));

In Java the default value of an int is zero. So that is why you see a lot of zeros.
Since you define the size of the array to be i which is more than what is required as the no of divisors would always be less than i.
So instead of printing the entire array you should only print it up to the total no of divisors for which you should a separate variable instead of using x.
Here is the modified version where I am using a separate index variable to keep track of number of divisors which start from 0. In the end you can just print the array up to the index
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int index = 0;
int x=2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[index] = x;
x = x + 1;
index= index + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.copyOfRange(drv, 0, index));
}
}

Set datastructure avoids duplicates, you can use that to overcome the problem of duplicate divisors getting added into the data structure.
import java.util.*;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
Set<Integer> divisors = new HashSet<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
divisors.add(x);
x = x + 1;
} else {
x = x + 1;
}
}
List<Integer> l = new ArrayList<>(divisors);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + l);
}
}

Use ArrayList to create Dynamic Array.
Below Code will help you.
Things to change In your Program.
import java.util.*;
take an ArrayList varible
call toString method on Arraylist Object
import java.util.*;
import javax.swing.JOptionPane;
public class NewClass3 {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
List<Integer> dvr = new ArrayList<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr.add(x);
x=x+1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + dvr.toString());
}
}

Related

My code runs, but the if statements are not printing their contents when I compare contents of two arrays

I am trying to write a simple mastermind game where a 4 digit number will be randomly selected by the computer and the user inputs a number over and over again until the correct number is found. I am trying to do this by passing the guessed number and the random number to their own separate arrays and then comparing them, position by position to see if they are similar. If two numbers are in the exact same spot
Example:
if guessArray[0] == numsArray[0] then the computer will print a *.
If two numbers are present but not in the exact same spot (eg. you made a guess of 2056 but the actual number is 1203) then one + should be printed. This cycle repeats until the number is guessed.
I've already asked a friend in person what the problem was and he couldn't figure it out. He knows the most code out of my friends so this was my next place to go.
Here is the full project. I did not write the ConvertInt2Array method. I found it on the internet.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Mastermind {
public static Random numGen = new Random();
public static void main(String [] args) {
Scanner Input = new Scanner (System.in);
int x = 0;
int number = 0;
int random = 0;
int guess = 0;
int y = 0;
int numArray[] = new int[4];
int guessArray[] = new int[4];
boolean isGuessed = false;
//Generate Random Number
for(x=0; x<=3; x++) {
int rand = Math.abs(numGen.nextInt());//Get the absolute value
random = (rand % 999 + 1);
numArray[x] = random;
number+=random;
}
while(isGuessed == false){
System.out.println("Guess a four digit random number");
guess = Input.nextInt();
guessArray = convertInt2Array(guess);
for(y=0; y<=3; y++) {
if(numArray[y] == guessArray[y]) {
System.out.print("*");
}
else if(Arrays.equals(numArray, y, y, guessArray, 0, guessArray.length) == true) {
System.out.print("+");
}
else {
}
if(guess==number) {
isGuessed = true;
}
}
}
System.out.println("You guessed it correctly!");
}
public static int[] convertInt2Array(int guess) {
String temp = Integer.toString(guess);
String temp2;
int temp3;
int [] gArray = new int[temp.length()];
for(int i=0;i<temp.length();i++) {
if (i!=temp.length()) {
temp2 = temp.substring(i, i+1);
} else {
temp2 = temp.substring(i);
}
temp3 = Integer.parseInt(temp2);
gArray[i] = temp3;
}
return gArray;
}
}
There may be more than one issue here, but here's a potential problem:
int rand = Math.abs(numGen.nextInt()); // Get the absolute value
random = (rand % 999 + 1);
This will usually result in random being a three-digit number. You mentioned you want this to be a four-digit number. Random.nextInt() can return any of the possible 232 integer numbers (from -2147483648 to 2147483647). To fix this, use a different Random.nextInt and specify your bounds:
int lowerBound = 1000;
int upperBound = 10000;
random = numGen.nextInt(upperBound - lowerBound) + lowerBound;
Let's break this down: numGen.nextInt(upperBound - lowerBound) evaluates to numGen.nextInt(9000), which will return a number between 0 (inclusive) and 9000 (exclusive), i.e. anything in the range 0-8999. You then add the lower bound of 1000 to ensure that random will be at least 1000 and up to 9999.
See the documentation for Random.nextInt(int bound).
Hopefully this gets you pointed in the right track.

factorable trinomial / polynomial

so I want to create a program that prints out a factorable quadratic equation when the user enters a value, c, and a = 1,. The program should determine all the possible Integer values of b so that the trinomial prints out in the form x^2 + bx + c
An example would be if the user entered -4 for c the program should print out:
x^2 - 4
x^2 - 3x - 4
So far this is what I have done with my code, I am trying to figure out how to execute the program but I really am having trouble of where to go from here. If anyone can offer some help that would be much appreciated!
public class FactorableTrinomials
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("A trinomial in standard form is ax^2 + bx +
c. \nIf a = 1, this program will output all factorable trinomials
given the entered c value.");
System.out.print("\nEnter an integer ā€œcā€ value: ");
int numC = scan.nextInt();
final int NUMA= 1;
int numB;
if (numC > 0)
{
int factors;
System.out.print("\nThe factors of " + numC + " are: ");
for(factors = 1; factors <= numC; factors++) //determines
factors and how many there are
{
if(numC % factors == 0)
{
System.out.print(factors + " ");
}
}
First, find the pairs of integer which multiplies to c.
all possible values of b will then be the sum of the pair of integer.
A simple way to find the pairs of integer is to loop 2 variables from -c to c and check if the product is c. eg:
for(int i = -1 * numC; i <= numC; i++) {
for(int j = -1* numC; j<= numC;j++) {
if(i * j == numC) {
int b = i + j;
//print solution, if b == 0 then don't print the second term
}
}
}

Adding a note to certain elements in an array if they meet requirements

So what my program is supposed to do...
Iterate through an array of 113 numbers
Print said numbers
But if..
number is odd print "odd" beside it
number is divisible by 5 print "hi five"
total number of x and its subsequent number (x+1) is divisible by 7 print "wow"
number is prime print "prime"
Currently my program will iterate through the numbers and print the ones that apply, and if two apply it will print it twice with different notes. What i would like to do is have it print all the numbers, then print the notes beside the numbers that apply. And if two conditions apply, print the notes beside each other and not on new lines.
ex. of what i would like it to do..
x: 5, odd, high five
Ive been trying different techniques from some examples i found but to no avail. Any direction or guidance would be greatly appreciated!
P.S. - i know i haven't implemented prime yet, my equation isn't right, thats next on my list.
Here is what i have so far..
import java.util.ArrayList;
public class Number {
public static ArrayList<Integer> getSequence() {
ArrayList<Integer> numbers = new ArrayList<Integer>(113);
for (int n = 0; n <= 113; n++) {
numbers.add(n);
}
return numbers;
}
public static boolean isOdd(int n) {
if (getSequence().get(n) % 2 != 0) {
System.out.println("x: " + n + ", x is odd");
}
return true;
}
public static boolean isDivisibleBy5(int n) {
if (getSequence().get(n) % 5 == 0) {
System.out.println("x: " + n + ", hi five");
}
return true;
}
public static boolean isDivisibleBy7(int n) {
int x = getSequence().get(n) + (getSequence().get(n) + 1);
if (x % 7 == 0 && x<113) {
System.out.println("x: " + n + ", wow");
}
return true;
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
System.out.println("x: " + n + ", prime");
if (n % 1 == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> nums = getSequence();
for (int n : nums) {
if(isOdd(n)) {
}
if(isDivisibleBy5(n)){
}
if(isDivisibleBy7(n)){
}
}
}
}
Instead of using Integer arraylist create a separate class which can hold Integer and ArrayList<String>. Then create your arraylist of that class type.
Make methods in your new class as follows
Method to insert the number
Method to retrieve the number
Method to insert a label to the array list.
Method to retrieve the ArrayList or String[]
This way you can easily overcome your problem.
One other method is to use a Map object(HashMap instead). Integer as the KEY and ArrayList<String> as the VALUE.

How to split an Integer into an Array using Java?

I apologise if this has already been asked before, but I was unable to find a conclusive answer after some extensive searching, so I thought I would ask here. I am a beginner to Java (to coding, in general) and was tasked with writing a program that takes a user-inputted 3 digit number, and adds those three digits.
Note: I cannot use loops for this task, and the three digits must all be inputted at once.
String myInput;
myInput =
JOptionPane.showInputDialog(null,"Hello, and welcome to the ThreeDigit program. "
+ "\nPlease input a three digit number below. \nThreeDigit will add those three numbers and display their sum.");
int threedigitinput;
threedigitinput = Integer.parseInt(myInput);
There are a number of ways, one of which would be...
String ss[] = "123".split("");
int i =
Integer.parseInt(ss[0]) +
Integer.parseInt(ss[1]) +
Integer.parseInt(ss[2]);
System.out.println(i);
another would be...
String s = "123";
int i =
Character.getNumericValue(s.charAt(0)) +
Character.getNumericValue(s.charAt(1)) +
Character.getNumericValue(s.charAt(2));
System.out.println(i);
and still another would be...
String s = "123";
int i =
s.charAt(0) +
s.charAt(1) +
s.charAt(2) -
(3 * 48);
System.out.println(i);
BUT hard coding for 3 numbers isn't very useful beyond this simple case. So how about recursion??
public static int addDigis(String s) {
if(s.length() == 1)
return s.charAt(0) - 48;
return s.charAt(0) - 48 + addDigis(s.substring(1, s.length()));
}
Output for each example: 6
you can use integer math to come up with the three numbers seperately
int first = threedigitinput / 100;
int second = (threedigitinput % 100) / 10;
int third = threedigitinput % 10;
If I understand your question, you could use Character.digit(char,int) to get the value for each character with something like -
int value = Character.digit(myInput.charAt(0), 10)
+ Character.digit(myInput.charAt(1), 10)
+ Character.digit(myInput.charAt(2), 10);
Classic example of using divmod:
public class SumIntegerDigits {
public static void main(String[] args) {
System.out.println(sumOfDigitsSimple(248)); // 14
System.out.println(sumOfDigitsIterative(248)); // 14
System.out.println(sumOfDigitsRecursive(248)); // 14
}
// Simple, non-loop solution
public static final int sumOfDigitsSimple(int x) {
int y = x % 1000; // Make sure that the value has no more than 3 digits.
return divmod(y,100)[0]+divmod(divmod(y,100)[1],10)[0]+divmod(y,10)[1];
}
// Iterative Solution
public static final int sumOfDigitsIterative(int x) {
int sum = 0;
while (x > 0) {
int[] y = divmod(x, 10);
sum += y[1];
x = y[0];
}
return sum;
}
// Tail-recursive Solution
public static final int sumOfDigitsRecursive(int x) {
if (x <= 0) {
return 0;
}
int[] y = divmod(x, 10);
return sumOfDigitsRecursive(y[0]) + y[1];
}
public static final int[] divmod(final int x, int m) {
return new int[] { (x / m), (x % m) };
}
}

Calculate e^x without inbuilt functions in Java

I am a beginner in Java and currently going through the "how to think like a computer scientist" beginners book. I am stuck with a problem in the iteration chapter. Could anyone please point me in the right direction?
When I use math.exp, I get an answer that is completely different from the answer my code obtains.
Note, it's not homework.
Here's the question:
One way to calculate ex is to use the infinite series expansion
ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
If the loop variable is named i, then the ith term is xi/i!.
Write a method called myexp that adds up the first n terms of this
series.
So here's the code:
public class InfiniteExpansion {
public static void main(String[] args){
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the power?");
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: "+myExp(x, power));
}
public static double myExp(double myX, double myPower){
double firstResult = myX;
double denom = 1;
double sum =myX;
for(int count =1;count<myPower;count++){
firstResult = firstResult*myX;//handles the numerator
denom = denom*(denom+1);//handles the denominator
firstResult = firstResult/denom;//handles the segment
sum =sum+firstResult;// adds up the different segments
}
return (sum+1);//gets the final result
}
}
The assignment denom = denom*(denom+1) is going to give a sequence as follows: 1, 1*2=2, 2*3=6, 6*7=42, 42*43=...
But you want denom = denom*count.
Let's say in general we just want to print the first n factorials starting with 1!: 1!, 2!, 3!, ..., n!. At the kth term, we take the k-1th term and multiply by k. That would be computing k! recursively on the previous term. Concrete examples: 4! is 3! times 4, 6! is 5! times 6.
In code, we have
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*i; // Here's the recursion mentioned above.
System.out.println(i+'! is '+a);
}
Try running the above and compare to see what you get with running the following:
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*(a+1);
System.out.println('Is '+i+'! equal to '+a+'?');
}
There are several errors here:
firstResult should start from 1, so that it goes 1+x+x^2 instead of 1+x^2+x^3
As timctran stated you are not calculating the factorial in a correct way.
To wrap up you can simplify your operations to:
firstResult = firstResult * myX / (count+1);
sum += firstResult;
Edit:
- I ran the code and saw that Math.exp(power) is printed instead of Math.exp(x)
- My first item is wrong since sum is initialized to myX.
Why make it complicated? I tried a solution and it looks like this:
//One way to calculate ex is to use the infinite series expansion
//ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
//If the loop variable is named i, then the ith term is xi/i!.
//
//Write a method called myexp that adds up the first n terms of this series.
import java.util.Scanner;
public class InfiniteExpansion2 {
public static void main(String[] args) {
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the value of I?"); // !
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: " + myCalc(x, power));
}
public static double fac(double myI) {
if (myI > 1) {
return myI * fac(myI - 1);
} else {
return 1;
}
}
public static double exp(double myX, double myE) {
double result;
if (myE == 0) {
result = 1;
} else {
result = myX;
}
for (int i = 1; i < myE; i++) {
result *= myX;
}
return result;
}
public static double myCalc(double myX, double myI) {
double sum = 0;
for (int i = 0; i <= myI; i++) { // x^0 is 1
sum += (exp(myX, i) / fac(i));
}
return sum;
}
}
If you want to think like an engineer, I'd do it like this:
keep it simple
break it into pieces
stick closely to the task (like I named the var myI, not myPower - seems clearer to me, for a start - that way you won't get confused)
I hope you like it!
I tried a solution and it looks like this:
public class Fact {
public int facto(int n){
if(n==0)
return 1;
else
return n*facto(n-1);
}
}
}
import java.util.Scanner;
public class Ex {
public static void main(String[] args){
Fact myexp=new Fact();
Scanner input=new Scanner(System.in);
int n=1;
double e=1,i=0,x;
int j=1;
System.out.println("Enter n: ");
n=input.nextInt();
System.out.println("Enter x: ");
x=input.nextDouble();
while(j<=n)
{
int a=myexp.facto(j);
double y=Math.pow(x,j)/(double)a;
i=i+y;
++j;
}
e=e+i;
System.out.println("e^x= "+ e);
}
}

Categories