Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Some phone usage rate may be described as follows:
The first minute of a call costs min1 cents.
Each minute from the 2nd up to 10th (inclusive) costs min2_10 cents each minute.
After the 10th minute, the call costs min11 cents for every additional minute.
You have s cents on your account before the call. What is
the duration of the longest call (in minutes rounded down to the
nearest integer) you can have?
Input data:
For min1 = 3, min2_10 = 1, min11 = 2, and s = 20, the output should be phoneCall(min1, min2_10, min11, s) = 14.
Here's why:
The first minute costs 3 cents, which leaves you with 20 - 3 = 17 cents. The total cost of minutes 2 through 10 is 1 * 9 = 9, so you can talk 9 more minutes and still have 17 - 9 = 8 cents. Each next minute costs 2 cents, which means that you can talk 8 / 2 = 4 more minutes.
Thus, the longest call you can make is 1 + 9 + 4 = 14 minutes long.
I'm not sure what's wrong with my code's logic here.
int phoneCall(int min1, int min2_10, int min11, int s) {
int sum = 0;
if (s >= min1) {
sum++;
s = s - min1;
for (int i = 1; i <= 9; i++) {
if (s >= min2_10) {
sum = sum++;
s = s - min2_10;
} else
break;
}
sum = sum + s / min11;
}
return sum;
}
In the if statement inside of your for loop you can do one of two things here to get your return to be 14.
Change the
sum=sum++; to
sum += 1; or remove the
sum= so it its just
sum++;
This should return 14 as the sum.
sum=sum++;
should be replaced with sum++;
Read more about operator precedence operator precedence and return values
Hello #ShubhamSahay You gotta make your code like this:
public static int phoneCall(int min1, int min2_10, int min11, int s) {
int sum=0;
if(s>=min1)
{
sum++;
s=s-min1;
for(int i=1;i<=9;i++)
{
if(s>=min2_10)
{
/*Change 1*/ sum++;
s=s-min2_10;
}
else
break;
}
/*Change 2*/ sum=sum+(s/min11);
}
return sum;
}
So here is why
1st Change: You need to do just sum++
2nd Change: you gotta put those that things in brackets
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Im having trouble only displaying the correct numbers, I know how to get the formula is have count-1 have 10/2 = 5 but now I want to count up from the start making it 10 15 20.
//Static void dispalySpace(double start, double end, int count){
// Display numbers between start and end inclusively
//The numbers are spaced equally
//Assume start < end and count is at least 2.
//displaySpace(10,20,3)
//The answer to the question is 10.0 15.0 20.0
while(min<max && count>=2)
for(int i=min; i<=max; i++) {
for(double j = count-1; j>=2; j++) {
System.out.print(j + " ");
}
System.out.print(i + " ");
}
System.out.println();
}
I keep just getting 10-20 displaying on a loop.
You first need to calculate the steep size, ie what do you have to add to min so that you end up with count numbers. For the first output, you won't have to add anything, so it's one less than count , ie
double step = (max-min) / count - 1;
That's what you have to add each step of the loop, starting with min , so
for (double i = 0; i <= max ; i = i + step) {
System.out.print(i) ;
}
My problem is that my code works perfectly when executed on an IDE But it exceeds the the time limit on Spoj. I am not getting any hint on how to make it more efficient.Spoj challenge
Here is my code :
import java.util.Scanner;
public class Factorial {
public static int getDecomposition(int a) {
int count = 0;
int result = a;
while (result % 5 == 0) {
result /= 5;
count++;
}
return count;
}
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
int sum[] = new int[testCases];
int nums[] = new int[testCases];
for (int i = 0; i < testCases; i++) {
nums[i] = scan.nextInt();
}
for (int i = 0; i < testCases; i++) {
for (int j = 5; j <= nums[i]; j = j + 5) {
sum[i] += getDecomposition(j);
}
System.out.println(sum[i]);
}
}
}
I’m thinking: Take 60 as an example (this is one of the example inputs in the linked challenges). You are correct in the assumption in your code that for each number from 1 to 60 you only need to consider how many times it’s divisible by 5, since there will always be enough numbers divisible by 2 that you will have this many zeroes. So how many of the numbers from 1 through 60 are divisible once by 5? Answer: 60 / 5 = 12. Out of those 12, how many are divisible by 5 once more? 12 / 5 = 2 (ignore any remainder). Add the 12 and the 2 (= 14) to record that until now we know that the factorial of 60 is divisible by 5 14 times. And out of those 2, how many are divisible a third time? 2 / 5 = 0. Once we’ve reached 0, we’re done. The answer was 14 (this agrees with the answer in the example in the link).
So make an algorithm out of this way of finding the answer. I think it will be somewhat faster than the program you have posted.
It may also be that you can find a not too complicated formula for the sum I am calculating so you can avoid looping altogether. And maybe you can find some inspiration here: Geometric progression.
I am new to Java programming and have tried a few problems on Project Euler. I somehow came up with my own problem of printing sequence of exponents of 3 and 5 and limit the result to below 1000. I have researched for 3 days to find the best approach to this problem but I could not find relevant articles. I have come across algorithms on exponential series but those were too advanced for my capability right now.
I would appreciate any help in solving this problem. Please see the code I have tried
public class Exponent {
public static void main (String[] args) {
// Declared integers for base and exponent
int i = 0; /* for base */
int n = 0; /* for exponent */
for (n=1; n<5; n++) {
for (i=1; i<=5; i++) {
if (i%3 == 0 || i%5 == 0) {
System.out.println(Math.pow(i,n));
}
}
}
}
}
This code prints out the following result:
3.0
5.0
9.0
25.0
27.0
125.0
81.0
625.0
My problem is that it is very apparent that I am forcing the exponent to print below 1000 by limiting the base and exponent value inside the loop
for (n=1; n<5; n++) //because n<=5 would print result for 5 power 5 which is 3125
I would like to somehow limit the result to below 1000 so not sure if this declaration is apt
int result = 1000; // result variable as 1000
Also, I want the code to print the output in alternates of 3 and 5 as shown below. My program prints the output in sequence of 3 and 5 respectively.
Desired output:
3.0
5.0
9.0
27.0
125.0
81.0
625.0
243.0
729.0
And stops there because the next value would exceed 1000.
I also wanted to know if there is any other approach instead of using Math.pow() method because it returns a double instead of an int. I would like to avoid the double value and just print as follows:
Without double:
3
5
9
27
81
125
243
625
729
Without using Math.pow() (and printing in different order ):
int[] bases = { 3, 5 };
long maxval = 1000L;
for (int base : bases) {
long value = base;
do {
System.out.println( value );
value *= base;
} while (value < maxval);
}
First create a double to store the result:
double result = 0;
Then create an infinite while loop which calculates the result using 3 and 5 and breaks out once result is above 1000.
while(true)
{
result = Math.pow(3, n);
if(result > 1000)
{
break;
}
System.out.println(((int)result));
result = Math.pow(5, n);
if(result < 1000)
{
System.out.println((int)result);
}
n++;
}
Since exponents of 3 are smaller than 5 don't break out until the maximum exponent in 3 is hit. Since the break does not occur don't print the 5 unless it is valid.
Also to print the double as an int value just cast it to an int.
EDIT:
If you are really worried about efficiency here is a faster solution:
public void calcExponents(int max)
{
int resultThree = 3;
int resultFive = 5;
while(resultThree < max)
{
System.out.println(resultThree);
if(resultFive < max)
{
System.out.println(resultFive);
}
resultThree *= 3;
resultFive *= 5;
}
}
You could also make the 3 and 5 arguments to take it one step further.
Why not check if the result is bigger than 1000, and just break out of the loop if it is?
if(Math.pow(i,n)>=1000)
break;
Hint:
3.0 = 3^1
5.0 = 5^1
9.0 = 3^2
25.0 = 5^2 // I assume you forgot it
27.0 = 3^3
125.0 = 5^3
81.0 = 3^4
625.0 = 5^4
243.0 = 3^5
729.0 = 3^6
and 3x is always smaller than 5x. So a single loop (for the x part) with two computations in the body of the loop one for 3 and one for 5 should do the job. You just have to use some condition for the less than 1000 part to avoid printing 55 and 56.
You could use a single loop, checking exponents for both 3 and 5 on each iteration, and printing each result that is less than 1000.
You just want to make sure that you break the loop once your 3's exceed 1000.
To print integer values, you can simply cast the result of Math.pow() to an int.
There are many different ways that one could write an algorithm like this. Here's a very simple (untested) example:
public class Exponent {
public static void main (String[] args) {
int i = 1; // or start at 0 if you prefer
// set the max value (could also be parsed from args)
int maxValue = 1000;
// the break condition also increments:
while (Math.pow(3, i++) < maxValue) {
int x3 = (int) Math.pow(3, i);
int x5 = (int) Math.pow(5, i);
if (x3 < maxValue) {
System.out.println(x3);
}
if (x5 < maxValue) {
System.out.println(x5);
}
}
}
}
int fnum = Integer.parseInt(split[0]);// holds 5
//split[] holds each line of the file.
double sum = fnum;// sum = 5
double i = 0.0;
double last = 0.0;
for(int j = 1; j<(split.length-1);j++)
{
i = Integer.parseInt(split[j].replaceAll("[^0-9]", ""));
if(split[j].charAt(0) == '*')
{
sum = sum * i;
}
else if(split[j].charAt(0) == '/')
{
sum = sum / i;
}
else if(split[j].charAt(0) == '+')
{
sum = sum + i;
}
else if(split[j].charAt(0) == '-')
{
sum = sum - i;
}
else if(split[j].charAt(0) == '%')
{
sum = sum % i;
}
}
System.out.println(sum);// Prints 1.0
}
}
/*
Actual Data File Imported
5
+ 3
* 7
+ 10
* 2
* 3
+ 1
% 11
Answer should be : 1
*/
Alright My code may look messy, but I tried hard on it. Gave up a few times but tried again. My question is for smaller data sets such as the one I imported and commented out on the code on the last few lines, work fine. But for bigger data sets it's all wrong why is that? I've tried making al my data sets double to get bigger values but somehow it's wrong?
I'm a beginner so far, any help would be greatly appreciated.
To be more specific on the problem I imported the file, I made it all a String, line by line, then I added it all in a String array so each line was in a string array for example split[1] would print + 3. Now after that I isolated the number and the symbol in the if loop wrapped in a forloop to go over all the sets. Now the if loop captures the symbols and then does the appropriate arithmetic. SomeHow it didn't though? And I used a double instead of an int for sum. That didn't help.I believe the if statement could be the issue.
Not sure if you still need the answer but, here's a tip:
The whole point of that specific exercise was to learn the modular arithmetic, which is that if you sum up/multiply the remainders of all of the numbers, you get the same answer as you would using the numbers given, that is if you apply the same number that's after % for all of them.
For example:
14
+ 78
* 9
* 3
+ 4
% 3
After all of the applied operations, the numbers above % 3 result in 2488.
And so 2488 % 3 = 1.
So if you apply % 3 to each one of the numbers, including the initial one, you get the same answer, using the same operations on their remainders of course and dividing the sum again by 3.
14 % 3 = 2
78 % 3 = 0
9 % 3 = 0
3 % 3 = 0
4 % 3 = 1
So, you get 2 + 0 * 0 * 0 + 1 which equals to 1.
And 1 % 3 = 1 which is the same as 2488 % 3 = 1.
My point being, you should apply modulo to every one of the numbers, so you get little numbers and don't even have the big ones you're having problems with.
Hope this was clear enough and hope it helps.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am working on Project Euler Problem 12. Could anyone provide any tips on how to improve my code so it executes in my life time?
public class HighlyDivisibleTriangularNumber {
public static void main(String[] args) {
int divisors = 0;
int count = 1;
while(divisors <= 501) {
long triNum = triangularNumber(count);
divisors = getFactors(triNum);
System.out.println(triNum+"_"+divisors);
count++;
}
}
private static int getFactors(long triNum) {
int divisors = 0;
while(triNum > 1) {
triNum = triNum / 2;
divisors++;
}
return divisors;
}
private static long triangularNumber(int i) {
long total = 0;
for(int k = 1; k <= i; k++) {
total += k;
}
return total;
}
}
1) triangular numbers
The first (and probably most important) optimization you can do is in how you compute the triangular numbers.
You can observe that the nth triangular number (let's call it t(n) ) is equal to n + t(n-1).
So each time you compute a triangular number, you can just take the triangular number before it and add n. This would lead to the naive recursive function :
private static long triangularNumber(int i) {
if(i == 1) return 1;
else return i+triangularNumber(i-1);
}
But this won't improve the performance much... to resolve this, I suggest you do some research on memoization and adapt the function I gave you (I won't give you the answer, this is an excellent exercise)
Now, on a regular computer you should have the answer to the problem in a reasonable time. But it can be improved a little better
2) counting divisors
Your function for counting divisors is wrong. What you should do is try to divide your number by successive natural numbers and see if the result is an natural integer.
private static int getFactors(long triNum) {
int divisors = 0;
for(int i = 1; i <= triNum; ++i) {
if(triNum%i == 0) // triNum is a multiple of 1 <=> i is a divisor of triNum
divisors++;
}
return divisors;
}
You can even improve this by counting only to the square root of trinum and adding two divisors each time. But there's a trick if you do this, I'll let you figure it out if you decide to try this.
Why do do recompute the triNum each time? Just add the difference each time (basically your count).
public static void main(String[] args) {
int divisors = 0;
int count = 1;
long truNum = 0;
while(divisors <= 501) {
triNum += count;
divisors = getFactors(triNum);
System.out.println(triNum+"_"+divisors);
count++;
}
}
Furthermore, your approach to count the factors is completely off. You are just searching for the first power of two to be greater than the given number. Read up on (prime)-factorization. Note that you need to account for the combinations of (prime) factors, too.
Example: 12
12 = 2 * 2 * 3
But the divisors of 12 are
1, 2, 3, 4 (= 2*2), 6 (= 2*3), 12
So in total there are 6 divisors of 12 and not 3 as the mere prime factorization may lead you to believe.