Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help with Java code!!! We are on the topic of using for and while loops.

ID: 642636 • Letter: I

Question

I need help with Java code!!! We are on the topic of using for and while loops. I can get the program to execute the factors of an integer, but I can't get it to state if an integer is prime and to do the rest of it. I've been working on this for a few days and I just can't get it. It is okay if the program crashes if any other value is inputted other than an integer.

Write a program that:

1) Asks the user for an integer greater than 1 and then prints out its divisors. If the number is prime, the program should print out a message saying so. So, for example, if the user enters 18 the program should print out the values 1, 2, 3, 6, 9, and 18. If the user enters 11, the program should indicate that it is prime (the only divisors are 1 and 11).

2) Asks the user for another integer greater than 1 and does the same thing (prints out the divisors or a message saying it is prime)

3) Prints a message indicating whether or not the two input integers are relatively prime. Two positive integers are relatively prime if they share no common divisors other than 1 (their greatest common factor is 1). For example, 8 and 15 are relatively prime. On the other hand, 12 and 9 are not relatively prime because they have a common divisor of 3.

Explanation / Answer

import java.io.*;

class PrintPrime {

public static void main(String args[])throws IOException {

boolean relativelyPrime = false;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter an integer:");

int a=Integer.parseInt(br.readLine());

int c=0;

//boolean firstPrime=false;

for(int i=1;i<=a;i++)

{

if(a%i==0)

{

System.out.println("The divisor of:"+a+"is"+i);

c++;

}

}

if(c==2)

System.out.println(a+"is Prime");

else

System.out.println(a+"Is Not Prime");

System.out.println("Enter an integer:");

int b=Integer.parseInt(br.readLine());

c=0;

//boolean firstPrime=false;

for(int i=1;i<=b;i++)

{

if(b%i==0)

{

System.out.println("The divisor of:"+b+"is"+i);

c++;

}

}

if(c==2)

System.out.println(b+"is Prime");

else

System.out.println(b+"Is Not Prime");

//Now Check Whether They Are Relatively Prime

int sma=0;   

if(a<b)

sma=a;

else

sma=b;

for(int i=2;i<=sma;i++)

{

if(a%i==0 && b%i==0)

relativelyPrime=false;

}

if(relativelyPrime==true)

System.out.println("The numbers are relatively prime");

else

System.out.println("The numbers are not relatively prime");

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote