How to find out if two numbers are relatively prime? - java

I'm trying to write a method that will calculate if two numbers are relatively prime for an assignment. I'm primarily looking for answers on where to start. I know there is a method gcd() that will do a lot of it for me, but the assignment is pretty much making me do it without gcd or arrays.
I kind of have it started, because I know that I will have to use the % operator in a for loop.
public static boolean relativeNumber(int input4, int input5){
for(int i = 1; i <= input4; i++)
Obviously this method is only going to return true or false because the main function is only going to print a specific line depending on if the two numbers are relatively prime or not.
I'm thinking I will probably have to write two for loops, both for input4, and input5, and possibly some kind of if statement with a logical && operand, but I'm not sure.

Well in case they are relatively prime, the greatest common divider is one, because - if otherwise - both numbers could be devided by that number. So we only need an algorithm to calculate the greatest common divider, for instance Euclid's method:
private static int gcd(int a, int b) {
int t;
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a;
}
And then:
private static boolean relativelyPrime(int a, int b) {
return gcd(a,b) == 1;
}
Euclid's algorithm works in O(log n) which thus is way faster than enumerating over all potential divisors which can be optimized to O(sqrt n).

Swift 4 code for #williem-van-onsem answer;
func gcd(a: Int, b: Int) -> Int {
var b = b
var a = a
var t: Int!
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a
}
func relativelyPrime(a : Int, b: Int) -> Bool{
return gcd(a: a, b: b) == 1
}
Usage;
print(relativelyPrime(a: 2, b: 4)) // false

package stack;
import java.util.Scanner; //To read data from console
/**
*
* #author base
*/
public class Stack {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // with Scanner we can read data
int a = in.nextInt(); //first variable
int b = in.nextInt(); //second variable
int max; // to store maximum value from a or b
//Let's find maximum value
if (a >= b) {
max = a;
} else {
max = b;
}
int count = 0; // We count divisible number
for (int i=2; i<=max; i++) { // we start from 2, because we can't divide on 0, and every number divisible on 1
if (a % i == 0 && b % i==0) {
count++; //count them
}
}
if (count == 0) { // if there is no divisible numbers
System.out.println("Prime"); // that's our solutions
} else {
System.out.println("Not Prime"); //otherwise
}
}
}
I think that, this is the simple solution. Ask questions in comments.

Related

Sum the products of numbers in range <a, b> that digits are prime number

I have got a little problem—I need to prepare program that (step by step information):
1)Gets from user two integers a and b and stop when b>a
2)Sum the products off all numbers in range < a, b > that digits are prime numbers
Example:
Input: 10, 15,
Output: 2340
(because 12*13*15 = 2340
2, 3 and 5 are prime numbers)
I feel like I stuck—I have got only a sum of the numbers (not the product) and not the prime but all of them.
public class Ex4 {
static int getNmbs() {
System.out.println("Enter number:");
Scanner sc = new Scanner(System.in);
return sc.nextInt();
}
public static int getSum(int a, int b) {
if (a > b)
return 0;
else
return a + getSum(a + 1, b);
}
public static void main(String[] args) {
int a = getNmbs();
int b = getNmbs();
int c =getSum(a,b);
System.out.println(c);
}
}
In order to solve this problem, you need to think of the step by step process:
First, accept two integer inputs, a and b.
Declare a variable to hold your product (the answer) and initialize it at 1. (If you initialize it at 0, then you will always get 0)
Now, assuming a < b, check to see if the digits of a are prime. IF it is, multiply your product by it and increment a. If it isn't, just increment a.
Rinse and repeat until a > b. And return the final product.
The trick here is going to be figuring out a way to check if the digits of a number are prime. I suggest using modulo division in increments of powers of 10 (for those more mathematically inclined) or converting the integer to a String and checking each character (using toCharArray).
Hope this helps!
This is a non recursive approach.
static boolean isProductPrime(int num){
int tmp = num % 10;
if( tmp < 2) return false;
for(int i = 2; i*i <= tmp; i++) //Instead of Math.SQRT
if(tmp % i == 0) return false;
return true;
}
public static void main(String [] args) {
Scanner myScanner = new Scanner(System.in);
int a = myScanner.nextInt();
int b = myScanner.nextInt();
int ans = 1;
for(int i = a ; i <= b ; i++){
if(isProductPrime(i))
ans *=i;
}
if( b < a)
ans = 0;
System.out.println(ans);
}

How to recursively calculate a number raised to a power?

I have tried:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
This does not yield a value as I'm not sure how to do that.
public int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
static int power(int x, int y)
{
// Initialize result
int temp;
if( y == 0) // Base condition
return 1;
temp = power(x, y/2); // recursive calling
if (y%2 == 0) //checking whether y is even or not
return temp*temp;
else
return x*temp*temp;
}
Well others have written solution which gives you correct answer but their time complexity is O(n) as you are decreasing the power only by 1. Below solution will take less time O(log n). The trick here is that
x^y = x^(y/2) * x^(y/2)
so we only need to calculate x^(y/2) and then square it. Now if y is even then there is not problem but when y is odd we have to multiply it with x. For example
3^5 = 3^(5/2) * 3^(5/2)
but (5/2) = 2 so above equation will become 3^2 * 3^2, so we have to multiply it with 3 again then it will become 3 * 3^(5/2) * 3^(5/2)
then 3^2 will be calculated as 3^(2/1) * (3^2/1) here it no need to multiply it with 3.
public static double pow(int a, int pow) {
if (pow == 0)
return 1;
if (pow == 1)
return a;
if (pow == -1)
return 1. / a;
if (pow > 1)
return a * pow(a, pow - 1);
return 1. / (a * pow(a, -1 * (pow + 1)));
}
Considering X as number and n as power and if both are positive integers
public static int power(int n, int X) {
if (n == 0) {
return 1;
} else if(n == 1) {
return X;
} else {
return X * power(n-1, X);
}
}
Let's re-write your function:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
First of all, lets change void to int.
Afterthat, when n equals to 1, we return the result as X, because X^1 = X:
static public int power(int n, int X) {
if (n>1) {
return X * power(n-1, X);
}
return X;
}
Scanner s = new Scanner(System.in) ;
System.out.println("Enter n");
int n = s.nextInt();
System.out.println("Enter x");
int x =s.nextInt();
if (n>0){
double pow =Math.pow(n,x);
System.out.println(pow);
}
While others have given you solutions in terms of code, I would like to focus on why your code didn't work.
Recursion is a programming technique in which a method (function) calls itself. All recursions possess two certain characteristics:
When it calls itself, it does so to solve a smaller problem. In your example, to raise X to the power N, the method recursively calls itself with the arguments X and N-1, i.e. solves a smaller problem on each further step.
There's eventually a version of the problem which is trivial, such that the recursion can solve it without calling itself and return. This is called base case.
If you are familiar with mathematical induction, recursion is its programming equivalent.
Number two above is what your code is lacking. Your method never returns any number. In the case of raising a number to a power, the base case would be to solve the problem for the number 0 as raising zero to any power yields one, so the code does not need to call itself again to solve this.
So, as others have already suggested, you need two corrections to your code:
Add a return type for the method.
State the base case explicitly.
public class HelloWorld{
public long powerfun(int n,int power,long value){
if(power<1){
return value;
}
else{
value = value * n;
return powerfun(n,power-1,value);
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println(hello.powerfun(5,4,1));
}
}
I've tried to add comments to explain the logic to you.
//Creating a new class
public class RecursivePower {
// Create the function that will calculate the power
// n is the number to be raised to a power
// x is the number by which we are raising n
// i.e. n^x
public static int power(int n, int x){
// Anything raised to the 0th power is 1
// So, check for that
if (x != 0){
// Recursively call the power function
return (n * power(n, x-1));
// If that is true...
}else{
return 1;
} //end if else
} //end power
// Example driver function to show your program is working
public static void main(String[] args){
System.out.println("The number 5 raised to 6 is " + power(5,6));
System.out.println("The number 10 raised to 3 is " + power(10,3));
} //end psvm
} //end RecursivePower

How to compare numbers in an INT value in Java?

I'm writing a code for an assignment for school but it requires me to compare two int values. For example, if you have the number 123 and the other number is 321, they have the same digits but are in different orders. Is there easy way of comparing them or do i have to make them into a string and compare them as string types? if its the latter, how could i compare two strings? Is there any way of doing this without an array?
By comparing int values, if you mean greater than, less than or equal you can do that like so.
int a = 123, b= 321;
if(a > b)
//a is greater than b (b is less than a)
if(a == b)
// a is equal to b
if(a < b)
// a is less than b (b is greater)
Could use some clarification, if you want to check if the number is reversed like you said in an example its called a palindrome.
You could reverse a number in the following if you had experience with loops and modulo(the %) in the following snippet.
int r = 0;
while(number != 0){
r = r * 10 + number % 10;
number /= 10; }
return r;
r would be that number reversed. If you input let's say 123 you would get 321 back, then you could compare it to the other to see if its just the reverse.
Let me know if you have any more questions and I'll try to answer!
To check if a number is arbitrarily mixed and not reversed to winning number, you could try the following.
Two numbers a and b, a is the winning number and b is the number the user chose.
a is 251 and b is 521.
You could do this on each number to separate them.
int p1,p2,p3;
p1 = num % 10;
p2 = num / 10 % 10;
p3 = num / 100 % 10;
This would separate ex. 251 into 2, 5, and then 1. Then you could add them as so doing the same process for the second. sum is p1 + p2 + p3 and sum2 is p4 + p5 + p6 for the second number. Provided the numbers are not reversed. Use the thing I mentioned before for that case to check if they are flipped.
if(sum == sum2)
//Numbers are mixed but you won!
This should work.
Certainly not the fastest solution, but the code is short and easy to understand.
public boolean arePalindromes(int a, int b){
//convert them to char arrays for easy sorting
char[] aryA = String.valueOf(a).toCharArray();
char[] aryB = String.valueOf(b).toCharArray();
//sort them
Collections.sort(aryA);
Collections.sort(aryB);
//put them back to strings for easy comparison
String strA = new String(aryA);
String strB = new String(aryB);
//compare
return strA.equals(strB);
}
Please try the following code (I have tested it), of which idea is borrowed from here and here. This solution still uses array.
public class CompareInt {
public static void main(String[] args) {
System.out.println(containSameDigits(123, 123));
System.out.println(containSameDigits(123, 321));
System.out.println(containSameDigits(123, 132));
System.out.println(containSameDigits(123, 323));
System.out.println(containSameDigits(123, 124));
System.out.println(containSameDigits(123, 111));
}
public static boolean containSameDigits(int x, int y) {
String xSorted = getSortedString(x);
String ySorted = getSortedString(y);
return xSorted.equalsIgnoreCase(ySorted);
}
public static String getSortedString(int x) {
String xSorted = "";
for (int digit = 0; digit < 9; digit++) {
for (int temp = x; temp > 0; temp /= 10) {
if (temp % 10 == digit) {
xSorted += digit;
}
}
}
return xSorted;
}
}
Output:
true
true
true
false
false
false

Using Recursion to reverse an integer without the use of strings

I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.
My first attempt:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
int tempRev = RevDigs(input/10);
if(tempRev >= 10)
reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
if(tempRev <10 && tempRev >0)
reverse = input%10*10 + tempRev;
if(tempRev == 0)
reverse = input%10;
return reverse;
}//======================
I also tried to use this, but it seems to mess up middle digits:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
if(RevDigs(input/10) == 0)
reverse = input % 10;
else
{
if(RevDigs(input/10) < 10)
reverse = (input % 10) *10 + RevDigs(input/10);
else
reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
}
return reverse;
}
I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.
How about using two methods
public static long reverse(long n) {
return reverse(n, 0);
}
private static long reverse(long n, long m) {
return n == 0 ? m : reverse(n / 10, m * 10 + n % 10);
}
public static void main(String... ignored) {
System.out.println(reverse(123456789));
}
prints
987654321
What about:
public int RevDigs(int input) {
if(input < 10) {
return input;
}
else {
return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
/* here we:
- take last digit of input
- multiply by an adequate power of ten
(to set this digit in a "right place" of result)
- add input without last digit, reversed
*/
}
}
This assumes input >= 0, of course.
The key to using recursion is to notice that the problem you're trying to solve contains a smaller instance of the same problem. Here, if you're trying to reverse the number 13579, you might notice that you can make it a smaller problem by reversing 3579 (the same problem but smaller), multiplying the result by 10, and adding 1 (the digit you took off). Or you could reverse the number 1357 (recursively), giving 7531, then add 9 * (some power of 10) to the result. The first tricky thing is that you have to know when to stop (when you have a 1-digit number). The second thing is that for this problem, you'll have to figure out how many digits the number is so that you can get the power of 10 right. You could use Math.log10, or you could use a loop where you start with 1 and multiply by 10 until it's greater than your number.
package Test;
public class Recursive {
int i=1;
int multiple=10;
int reqnum=0;
public int recur(int no){
int reminder, revno;
if (no/10==0) {reqnum=no;
System.out.println(" reqnum "+reqnum);
return reqnum;}
reminder=no%10;
//multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
i++;
no=recur(no/10);
reqnum=reqnum+(reminder*multiple);
multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
return reqnum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=123456789;
Recursive r= new Recursive();
System.out.println(r.recur(num));
}
}
Try this:
import java.io.*;
public class ReversalOfNumber {
public static int sum =0;
public static void main(String args []) throws IOException
{
System.out.println("Enter a number to get Reverse & Press Enter Button");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int number = Integer.parseInt(input);
int revNumber = reverse(number);
System.out.println("Reverse of "+number+" is: "+revNumber);
}
public static int reverse(int n)
{
int unit;
if (n>0)
{
unit = n % 10;
sum= (sum*10)+unit;
n=n/10;
reverse(n);
}
return sum;
}
}

Recursive Exponent Method

public static int exponent(int baseNum) {
int temp = baseNum *= baseNum;
return temp * exponent(baseNum);
}
Right now the method above does n * n into infinity if I debug it, so it still works but I need this recursive method to stop after 10 times because my instructor requires us to find the exponent given a power of 10.
The method must have only one parameter, here's some examples of calling exponent:
System.out.println ("The power of 10 in " + n + " is " +
exponent(n));
So output should be:
The power of 10 in 2 is 1024
OR
The power of 10 in 5 is 9765625
Do something like
public static int exp(int pow, int num) {
if (pow < 1)
return 1;
else
return num * exp(pow-1, num) ;
}
public static void main (String [] args) {
System.out.println (exp (10, 5));
}
and do not forget the base case (i.e a condition) which tells when to stop recursion and pop the values from the stack.
Create an auxiliary method to do the recursion. It should have two arguments: the base and the exponent. Call it with a value of 10 for the exponent and have it recurse with (exponent-1). The base case is exponent == 0, in which case it should return 1. (You can also use exponent == 1 as a base case, in which case it should return the base.)
The following is what my instructor, Professor Penn Wu, provided in his lecture note.
public class Exp
{
public static int exponent(int a, int n)
{
if (n==0) { return 1; } // base
else // recursion
{
a *= exponent(a, n-1);
return a;
}
}
public static void main(String[] args)
{
System.out.print(exponent(2, 10));
}
}
Shouldn't it have 2 parameter and handle exit condition like below?
public static int exponent(int baseNum, int power) {
if(power == 0){
return 1;
}else{
return baseNum * exponent(baseNum, power-1);
}
}
For recursion function, we need to :
check stopping condition (i.e. when exp is 0, return 1)
call itself with adjusted condition (i.e. base * base^(n-1) )
Here is the code.
public class Test
{
public static int exponent(int baseNum, int exp)
{
if (exp<=0)
return 1;
return baseNum * exponent(baseNum, --exp);
}
public static void main(String a[])
{
int base=2;
int exp =10;
System.out.println("The power of "+exp+" in "+base+" is "+exponent(base,exp));
}
}
Don't forget , for each recursive function , you need a base case. A stop condition`
static double r2(float base, int n)
{
if (n<=0) return 1;
return base*r2(base,n-1);
}
I came here accidentally, and I think one could do better, as one would figure out easily that if exp is even then x^2n = x^n * x^n = (x^2)^n, so rather than computing n^2-1 recursions, you can just compute xx and then call pow(x,n) having n recursions and a product. If instead the power is odd, then we just do xpow(x, n-1) and make the power even again. But, as soon as now n-1 is even, we can directly write xpow(xx, (n-1)/2) adding an extra product and using the same code as for the even exponent.
int pow_( int base, unsigned int exp ) {
if( exp == 0 )
return 1;
if( exp & 0x01 ) {
return base * pow_( base*base, (exp-1)/2 );
}
return pow_( base*base, exp/2 );
}

Categories