I've written this code that computes the sum of the positive divisors, and all the values have to be to the power of a.
For instance:
sigma(0,14) = 1^0 + 2^0 + 7^0 + 14^0 = 4;
sigma(2,12) = 1^2 + 2^2 + 3^2 + 4^2 + 6^2 + 12^2 = 210.
sigma(a, b).
I have tried different versions but I don't know how to add the power function.
try {
int a = Integer.parseInt(input1.getText());
int b = Integer.parseInt(input2.getText());
int result1 = 0;
for (int i = 2; i <= Math.sqrt(b); i++)
{
if (b % i == 0)
{
if (i == (b / i))
result1 += i;
else
result1 += (i + b / i);
}
}
result.setText(String.valueOf(result1 + b + 1));
}
}
In Java the ^ character means XOR.
The power function is provided by the Math.pow() method.
So 3^2 would be Math.pow(3, 2).
If you wanted to implement it yourself for integers, you could do it simply like this:
double power(int a, int b) {
int pow = (b < 0) ? -b : b;
double result = 1;
for (int i = 0; i < pow; i++) {
result *= a;
}
return (b < 0) ? 1 / result : result;
}
But I wouldn't do it myself. It gets a bit more complicated for floating points, and Java has a native underlying implementation which is much faster.
IntStream delivers beautiful concise calculation.
static int sigma(int exp, int num) {
IntStream.rangeClosed(1, num) // 1, ..., num
.filter(k -> num % k == 0) // Only divisors
.map(k -> pow(k, exp))
.sum();
}
static int pow(int k, int exp) {
if (exp == 0) {
return 1;
}
int squareRoot = pow(k, exp/2);
int n = squareRoot * squareRoot;
return (exp % 2) == 0 ? n : n*k;
}
The power calculation can be optimized by not using exp# multiplications of k but square roots.
For those interested in program transformation:
pow(k, exp) needs only to rely on exp with recursion to exp/2 (integer division). So you could turn the code inside out, have a vector of divisors,
and operate on that.
If you want to implement it without using Math.pow() you can simply follow the mathematical definition of the exponentiation for a positive exponent:
public static long exp(int a, int b){ //computes a^b
long result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
I would recommend that you use Java lambdas to accomplish what you're looking for.
Taking an input and returning a List of positive divisors seems useful on its own.
Raising every entry to a power could be done easily with a lambda.
Keep the two functions separate. Take a more functional approach.
Here is a simple code for you:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
List<Integer> listOfBs = new ArrayList<>();
System.out.println("Input your a");
int a = scanner.nextInt();
System.out.println("Input your b");
int b = scanner.nextInt();
int sqrt = (int) Math.sqrt(b);
for (int i = 1; i <= sqrt; i++) {
if (b % i == 0) {
listOfBs.add(i);
int d = b / i;
if (d != i) {
listOfBs.add(d);
}
}
}
int sigma = 0;
for(int e : listOfBs)
{
sigma += Math.pow(e,a);
}
System.out.println("Your sigma function is: "+sigma);
}
}
Related
How I find among all pairs a and b with a "least common multiple" LCM(a,b) = 498960 and a "greatest common divisor" GDM(a, b) = 12 a pair with minimum sum a + b?
I solved this with O(n^2) time:
public class FindLcmAndGcdClass {
private int findGcd(int a, int b) {
if (a % b == 0) {
return b;
}
return findGcd(b, a % b);
}
private int findLcm(int a, int b, int gcd) {
return (a * b) / gcd;
}
private void run() {
int minSum = Integer.MAX_VALUE;
int foundNumberOne = 0;
int foundNumberTwo = 0;
for (int i = 12; i <= 498960; i += 12) {
for (int j = i; j <= 498960; j += 12) {
int gcd;
if (i < j) {
gcd = findGcd(j, i);
} else {
gcd = findGcd(i, j);
}
int lcm = findLcm(i, j, gcd);
if (gcd == 12 && lcm == 498960 && i + j < minSum) {
minSum = i + j;
foundNumberOne = i;
foundNumberTwo = j;
}
}
}
System.out.println(minSum);
System.out.println(foundNumberOne);
System.out.println(foundNumberTwo);
}
public static void main(String[] args) {
var o = new FindLcmAndGcdClass();
o.run();
}
}
And it executes quite slowly! I guess the problem can be solved with Dynamic Programming. Can anyone help with more fast solution?
I am not sure if this question can be solved with dynamic programming, but I think of a solution with time complexity O(sqrt(LCM * GCD)).
It is well known that for any two integers a and b, LCM(a, b) * GCD(a, b) = a * b. Therefore, you can first calculate the product of the gcd and lcm, (which is 5987520 in this question). Then for all its factors under sqrt(LCM * GCD), let a be one of the factors, then b = LCM * GCD / a. Test if gcd(a, b) = the required gcd, if so calculate the sum a + b, then find the minimum among the sums, and you are done.
I have the following program
The sum of squares 1^2 + 2^2 + … + N^2 is calculated as:
Example output:
java SumSquares 2 = 5
java SumSquares 3 = 14
java SumSquares 1000000 = 333333833333500000
Here's what I have so far:
int N = Integer.parseInt(args[0]);
int sum = 0;
long R;
for (int i = 1; i <= N; i++) {
R = i * i;
if (i != R / i) {
System.err.println("Overflow at i = " + i);
System.exit(1);
}
sum += R;
}
System.out.println(sum);
My output is java SumSquares 100000000
Overflow at i = 46341
As 46341^2 passes MAX INT.
I just can't get the program to out put the below instructions, any ideas on how to get
java SumSquares 100000000
Overflow at i = 3024616
I could change the ints to longs but that would negate the need for the overflow checking.
From specification:
The computation will overflow. I need to exactly determine the point in the summation where the overflow happens, via checking whether the new sum is (strictly) less than the old sum.
java SumSquares 100000000
Overflow at i = 3024616
Note that the above must be achieved by a general overflow-handling in the loop, not by some pre-determined input-testing. So that when the integer-type used for the summation is replaced by some bigger type, your program will fully use the new extended range.
Just to clarify:
Is it possible to get the output
java SumSquares 100000000
Overflow at i = 3024616
As per the specification.
You have 2 errors:
R = i * i still performs the multiplication using int math, and doesn't widen the value to long until after multiplication has already overflowed to a negative value.
You need to cast at least one of them to long, e.g. R = i * (long) i.
if (i != R / i) is not the right test for overflow. Simply check if the long value exceeds the range of int: if (r > Integer.MAX_VALUE)
static int sumOfSquares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
long r = i * (long) i;
if (r > Integer.MAX_VALUE) {
System.err.println("Overflow at i = " + i);
System.exit(1);
}
sum += r;
}
return sum;
}
Test
System.out.println(sumOfSquares(2));
System.out.println(sumOfSquares(3));
System.out.println(sumOfSquares(1000000));
Output
5
14
Overflow at i = 46341
Another way to guard against overflow is to use the Math.multiplyExact() and Math.addExact() methods.
static int sumOfSquares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
int r = Math.multiplyExact(i, i);
sum = Math.addExact(sum, r);
}
return sum;
}
Output
5
14
Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.addExact(Math.java:825)
at Test.sumOfSquares(Test.java:12)
at Test.main(Test.java:6)
Or catch the exception if you want a better error message:
static int sumOfSquares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
try {
int r = Math.multiplyExact(i, i);
sum = Math.addExact(sum, r);
} catch (#SuppressWarnings("unused") ArithmeticException ignored) {
System.err.println("Overflow at i = " + i);
System.exit(1);
}
}
return sum;
}
Output
5
14
Overflow at i = 1861
Without having to use longs, you can check if the multiplication of two integers will overflow before actually doing the operation:
int a = 500000; //or -500000
int b = 900000; //or -900000
System.out.println(isOverflowOrUnderflow(a, b));
//Returns true if multiplication of a, b results in an overflow or underflow..
public static boolean isOverflowOrUnderflow(int a, int b) {
return ((a > Integer.MAX_VALUE / b) || (a < Integer.MIN_VALUE / b) || ((a == -1) && (b == Integer.MIN_VALUE)) || ((b == -1) && (a == Integer.MIN_VALUE)));
}
Example using your code:
public class Main {
public static void main (String[] args) {
int N = Integer.parseInt(args[0]); //Where args[0] = "1000000"..
int sum = 0;
long R;
for (int i = 1; i <= N; i++) {
if (Main.isOverflowOrUnderflow(i, i)) {
System.err.println("Overflow at i = " + i);
System.exit(1);
}
R = i * i;
sum += R;
}
System.out.println(sum);
}
public static boolean isOverflowOrUnderflow(int a, int b) {
return ((a > Integer.MAX_VALUE / b) || (a < Integer.MIN_VALUE / b) || ((a == -1) && (b == Integer.MIN_VALUE)) || ((b == -1) && (a == Integer.MIN_VALUE)));
}
}
Outputs:
Overflow at i = 46341
Command exited with non-zero status 1
Let's say that I want to calculate the square root of 8. There are two ways to display the result as you can see here:
I think that the best way I have to obtain the second solution is this:
I want to try do display in my Java application 2√2 instead of 2,828427... and so I thought to develop a class following these steps. Let's consider the square root of 8.
Get the prime factors of 8 (2*2*2)
Count the exponent and try to export them (2^2 * 2 --> 2√2)
I have developed, as you can see below, a code that outputs the factors. If you input 8, the method estraiRadice() will output 2 * 2 * 2, which is correct.
private int b = 2;
public String estraiRadice(double x) {
String resRad = "";
int[] exponents = new int[100];
//Scomposizione in fattori primi
while (x > 1) {
if ((x % b) == 0) {
x /= b;
resRad += String.valueOf(b) + " * ";
} else {
b++;
}
}
return resRad;
}
The second step is giving me problems because I don't know exactly how to do create the power of a number and export it from the square root. I mean: how can that √2*2*2 become a √4*2 and then 2√2?
I thought that I could store in an array the exponent for each base and then try to export it somehow. Do you have any advice?
Try this:
public static int[] squareRoot(int number) {
int number1 = number;
List<Integer> roots = new ArrayList<>();
int coefficient = 1;
for (int i = 2; i < number1; i++) {
if (number1 % (i * i) == 0) {
roots.add(i);
number1 /= i * i;
for (int j = 2; j < number1; j++) {
if (number1 % (j * j) == 0) {
roots.add(j);
number1 /= j * j;
}
}
}
}
for (int root : roots) coefficient *= root;
return new int[]{coefficient, number1};
}
You can call it like this:
System.out.println(squareRoot(96)[0] + "√" + squareRoot(96)[1]);
You can use a HashMap to store prime number power pairs
HashMap<Integer,Integer> getRoots(int x)
{
HashMap<Integer,Integer> retval = new HashMap<Integer,Integer>();
int i=2;
while(i<=x)
{
int power = 0;
while( x%i == 0)
{
power++;
x /= i;
}
if(power>0)
{
retval.put(i,power);
}
if(x==1)
{
break;
}
i++;
}
return retval;
}
This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}
I am trying to find the perfect number by find out all their divisors. If their sum is equal to the number, then print out the the number. But apparently it's not working.
import acm.program.*;
public class PerfectNumber extends ConsoleProgram{
public void run() {
for (int n = 1; n < 9999; n++) {
for (int d = 2; d < n - 1; d++) {
//d is the potential divisor of n, ranging from 2 to n-1,//
//not including 1 and n because they must be the divisors.//
if (isPerfectNumber(n,d))
print(n );
}
}
}
//method that determines if n is perfect number.//
private boolean isPerfectNumber(int n, int d) {
while (n % d == 0) {
int spd = 1;
spd += d;
if (spd == n) {
return true;
} else {
return false;
}
}
}
}
Looking at the code in your case will return false most of the times. I think what you were looking for is a bit wrong.
Because d is smaller than n, and n divided by d will always be grater than 0. Also in that loop you never change the value of d.
A solution might be:
public void run() {
for (int n = 1; n < 9999; n++)
{ spd=1;
for (int d = 2; d <= n/2; d++) { //no need to go further than n/2
//d is the potential divisor of n, ranging from 2 to n-1,//
if(n%d==0) spd+=d; //if n divides by d add it to spd.
}
if(spd==n) print(n);
}
Try this and let me know if it works for you.
I find something cool here : http://en.wikipedia.org/wiki/List_of_perfect_numbers. You should the much faster using this formula: 2^(p−1) × (2^p − 1). You can see the formula better on the wikilink.
Method isPerfect should probably be something like that:
public static boolean isPerfect(int number) {
int s = 1;
int d = number / 2;
for(int i = 2; i <= d; i++) {
if (number % i == 0) s += i;
}
return s == number;
}