Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
import acm.program.*;
public class Practice3 extends ConsoleProgram
{
public static int powersOf2(int k) {
int x = 0;
while (k < 1000) {
x = k;
k *= 2;
}
return x;
}
public void run()
{
println(powersOf2(1));
println(powersOf2(0));
println(powersOf2(2));
println(powersOf2(-1));
println(powersOf2(3000));
}
I don't think I really get right values from powersOf2. Only 512 is displayed when I run program. And if I run it by each println, it gives me:
512
none
512
none
0
Is there something wrong? or values are correct?
public static int powersOf2(int k){
int x=1;
while (k > 0){
x *= 2;
k--;
}
return x;
}
The method powersOf2 is completely wrong. It will always return the biggest power of 2 less then 1000. You should take into account the input argument and perform as many multiplications by two:
public static int powersOf2(int k){
int x=1;
for (int i = 0; i < k; ++i) {
x *= 2;
}
return x;
}
It won't always return 512. It depends on your initial parameter.
If you pass k as a parameter, it returns k*2^n which is less than 1000 and k*2^(n+1) is more than 1000. (so with parameter 0 method will loop forever)
So if you pass 3, as its parameter it would return 768 and if you pass any number between 501 and 999 the method will be your initial parameter.
For negative number the method multiples the input parameter by 2, until a underflow occurs, if the result of underflow is greater than 1000 it will return the last negative number, otherwise, it will continue the iterations with same exact logic as a positive parameter less than 1000.
So what do you expect your program do?
Your program goes into infinite loop because when you try to call the method with 0 as input. k is always 0 and it is always less than 1000. You need to exclude 0 in your program because it does not make sense having powers of 2 for 0
I think you want to take care of the special cases- for 0, it should be 1, for negative, you should treat it as a negative power, hence you should use double instead of int for your variable. And here is the code:
public class Practice3 extends ConsoleProgram
{
public static double powersOf2(int k) {
double x = 0;
if(k == 0) {
return 1;
}
double answer = 2;
if(k>0){
for(int i = 0; i < k; i++) {
answer *= 2;
}
return answer;
} else {
answer = 1;
for(int i = 0; i > k; i--) {
answer /= 2;
}
return answer;
}
}
You are always multiplying k by 2 until it exceeds 1000. So, for all 1000 > k > 0 it returns 512, otherwise it returns 0.
public static int powersOf2(int k){
int x=1;
for (i=0; i < k; i++){
x*=2;
}
return x;
}
Related
This is my code for the Codewars problem (Java) yet I cannot make it work. I'm pretty sure I've made a stupid mistake somewhere because of my lack of experience (coding for 4 months)
public static int zeros(int n) {
int f = 1;
int zerocount = 0;
for(int i = 2 ; i <= n; i++){
f *= i;
}
String factorial = String.valueOf(f);
String split [] = factorial.split("");
for(int i = 0; i < split.length; i++){
String m = split[i];
if(m.equals( "0")){
zerocount ++;
}
else {
zerocount = 0;
}
}
return zerocount;
}
}
In fact, you do not need to calculate the factorial because it will rapidly explode into a huge number that will overflow even a long. What you want to do is count the number of fives and twos by which each number between 2 and n can be divided.
static int powersoffive(int n) {
int p=0;
while (n % 5 == 0) {
p++;
n /= 5;
}
return p;
}
static int countzeros(int n) {
int fives = 0;
for (int i = 1; i <= n; i++)
fives += powersoffive(i);
return fives;
}
Note: Lajos Arpad's solution is superior.
As pointed out by other users your solution will probably not be accepted because of the exploding factorial you are calculating.
About the code you wrote there are two mistakes you have made:
You are calculating the factorial in the wrong way. You should start with i = 2 in the loop
for(int i = 2; i <= n; i++){
f *= i;
}
Also in Java you cannot compare strings using ==. This is not valid
if(m == "0")
You should compare them like this
if(m.equals("0"))
Anyway this is how I would have resolved the problem
public static int zeros(int n) {
int zerocount = 0;
for (int i = 5; n / i > 0; i *= 5) {
zerocount += n / i;
}
return zerocount;
}
A zero in a base-10 representation of a number is a 2*5. In order to determine the number of trailing zeroes you will need to determine how many times can you divide your number with ten, or, in other words, the minimum of the sum of 2 and 5 factors. Due to the fact that 5 is bigger than 2 and we go sequentially, the number of fives will be the number of trailing zeroes.
A naive approach would be to round down n/5, but that will only give you the number of items divisible with 5. However, for example, 25 is divisible by 5 twice. The same can be said about 50. 125 can be divided by 5 three times, no less.
So, the algorithm would look like this:
int items = 0;
int power = 5;
while (power < n) {
items += (int) (n / power);
power *= 5;
}
Here small numbers are in use in relative terms, but it's only a proof of concept.
You do need to use brute force here and you integers will overflow anyway.
With multiplication trailing zero appears only as the result of 2*5.
Now imagine the factorial represented by a product of it's prime factors.
Notice that for every 5 (five) we will always have 2 (two).
So to calculate the number of zeroes we need to calculate the number of fives.
That can be implemented by continuously dividing N by five and totaling results
In Java code that will be something like this:
static int calculate(int n)
{
int result = 0;
while (n > 0 ) {
n /= 5;
result += n;
}
return result;
}
Hi there sorry for this noob question. I'm Mario and may I ask if my program is correct for recursive and non-recursive function for Fibonacci Secquence nth Value.
static int recursiveMethod(int num)
{
if (num <= 1)
return num;
return recursiveMethod(num-1) + recursiveMethod(num-2);
}
static int nonRecursiveMethod(int num) {
if (num == 0) {
return 0;
}
if (num == 1) {
return 1;
}
int first = 0;
int second = 1;
int nth = 1;
for (int i = 2; i <= num; i++) {
nth = first + second;
first = second;
second = nth;
}
return nth;
}
For summary:
Example I inputted 6 as my nth value. Then the outputs are
RECURSIVE: 8 then
NON-RECURSIVE: 1 1 2 3 5 8
Is that correct?
Calling nonRecursiveMethod will produce the same output as calling recursiveMethod. The result is correct, recursiveMethod is inefficient for big numbers, though, because it will compute results for lower numbers again and again.
yeah both the approaches are fine. What I would like to suggest here is rather than calling function for every "num" you can pre-compute and store the values(Dynamic Programming).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I was asked a question to find a shortest distance between factors of a number without using arrays, any data structures or string in Java. For example if 13013 is passed to a method it should return 2, since the factors of 13013 are 1*7*11*13*13 and the shortest distance between two different number is 13-11=2, one more example if 10 is passed it should return 1, since factors of 10 are 1*2*5 and the shortest distance is (2-1) which is 1. What i found was if even number is passed it should always return 1, since 2, and 1 is always involved in the factor and (2-1)=1, if prime is passed it will be (number-1), since prime is only divisible by itself and 1, and if odd is passed mostly it is 2 Since (3-1)=2, but I am not being able to find for all numbers.
This is what I have till this point, thank you all
static int findDistance(int numberPassed)
{
boolean isPrime=true;
int returnValue=0;
if(numberPassed % 2==0)
{
//If it is even there must be 2 and 1 as a factor therefore 2-1=1
returnValue=1;
}
else
{
for(int i=2;i<numberPassed;i++)
{
if(numberPassed % i==0)
{
//if number is divisible by any except by 1 and itself
//it is prime
isPrime=false;
break;
}
}
if(isPrime && numberPassed!=1)
{
//If it is prime then return value should be numberPassed-1
//since factor of prime are 1 and itself, so shortest distance
//numberPassed-1
returnValue=numberPassed-1;
}
else
{
//The problem is here if the number is not prime and is odd
//since shortest distance differes now, for value divisible by 3
//it should be 3-1=2, but there are many other cases
returnValue=2;
}
}
return returnValue;
}
static int findDistance(int a)
{
//variables needed for calculation
int temp=a;
int fact=1;
int distance=0;
int shortestDistance=a;
int lastFact=1;
while(temp>1)
{
//If value is divisible by fact variable
if(temp % fact==0)
{
//If last fact does not equal current fact
if(lastFact!=fact)
{
distance=fact-lastFact;
lastFact=fact;
}
//divide by fact
temp=temp/fact;
//reassign the fact to 1 so that it can start from beginning
fact=1;
//if distance is not zero and shortestDistance is bigger
if(shortestDistance>distance && distance !=0)
{
//now the shortest distance is the distance
shortestDistance=distance;
}
}
fact++;
}
return shortestDistance;
}
public static int minDistance(int num){
int fact1 = 1;
int minDist = num;
int fact2 = 0;
for(int i=2; i<num; i++){
if (num%i==0){
fact2 = i;
if((fact2-fact1)<=minDist){
minDist = fact2-fact1;
fact1 = fact2;
}
}
}
return (minDist);
}
public class Demo {
public static void main(String[] args) {
System.out.println("Result: " + minDistance(1001));
}
public static int minDistance(int n) {
int minDistance = n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (n % i == 0 && n % j == 0) {
if (i > j) {
int distance = i - j;
if (distance < minDistance) {
minDistance = distance;
}
}
}
}
}
return minDistance;
}
}
Here,two for-loops are used: Outer for-loop is used to take one value at a time and calculate distance between two value(Second value is obtained from Inner for-loop) and stored in distance variable. Since minimum distance between the factors of the number will always be less than itself, so the minDistance is initialized to the number itself. If the distance is less than minDistance value then minDistance is reset to new distance value.
How do I calculate the sum of all the even numbers up to a certain number entered by the user using Java?
The naive solution would be to start from 0 and keep adding even numbers like this:
public static int square (int x)
{
int sum= 0;
for(int i = 0; i <= x; i+=2) sum += i;
return sum;
}
but you don't have to do this. This is a simple arithmetic sequence and to calculate the sum you can use the formula sum= n(a1 + an)/2 where a1 is the first term, 'an' is the last term and n is the total number of terms in the sequence.
for you a1 is 2, an is the parameter and you can calculate n by dividing the parameter (rounded down to closest even number) by 2.
This way your function will be:
public static int square (int x)
{
//you can do error checking if you want, x has to be non negative
if( (x%2) !=0) x--;
//x is guaranteed to be even at this point so x/2 is also an int
int sum= x/2 *(1+x/2);
return sum;
}
The trick to this question is "even numbers". By using % (the modulus operator) you can find these numbers easy. If you are curious about Mod, check this link https://msdn.microsoft.com/en-us/library/h6zfzfy7(v=vs.90).aspx
Using the square method you currently have and making a few modifications you can achieve the solution.
static int square (int x)
{
int result = x;
for(int i = 0; i < x; i++){
if(i%2 == 0){
result += i
}
}
return result;
}
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I faced an interview. where I was asked the following question
Write a function in any of programming language that computes the nth power of a number w/o using + * or ^ or declaring a new variable inside the function or using any library function (eg Math lib in java).
I have used pow function of java Math.pow(a, b)
Thanks
They're asking whether you understand recursion. Considering x ^ k for some integer k,
when k < 0, xk = xk+1 / x
when k = 0, xk = 1
when k > 0, xk = xk-1 * x
Turning this into code shouldn't be too bad. Let's use multiplication for now, and take it out later.
double recursivePower(double x, int k) {
if (k < 0) {
return power(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return power(x, --k) * x;
}
}
Now, to get rid of the multiplication. Since n * m = n / (1/m), we can rewrite the last calculation as power(x, --k) / (1/x):
double recursivePower(double x, int k) {
if (k < 0) {
return recursivePower(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return recursivePower(x, --k) / (1 / x);
}
}
Fractional exponents could probably be done in the same style. If they want irrational exponents to be handled in the same way, I'd ask for Google and a fair amount of time to think about the problem.
static public int power(int value, int pow){
if(pow == 0) return 1;
return value * power(value, pow -1);
}
Done in JavaScript:
function power(num,pow){
if (pow == 0) return 1
num /= 1/(power(num,--pow))
return num
}
Call it like:
power(2,0) // -> 1
power(5,2) // -> 25
power(7,3) // -> 343
I feel like inverse division is cheating the no * operator rule, but eh, maybe that's what they were looking for.
I am using java programming language. The interviewer restricted you to declare a new variable inside the method better you pass it to the function. The interviewer didnt restrict you to use division operator (/) so you can use that.
static double getNthPowerOfNumber(double originalNumber,
int power) {
if (power == 0) {
return 1;
}
if (originalNumber == 0) {
return 0;
} else {
originalNumber/=1/getNthPowerOfNumber(originalNumber, --power);
return originalNumber;
}
}
if you want to get 5th power of a number 3 then write System.out.println("4..double..." + getNthPowerOfNumber(4, 1));