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 6 years ago.
Improve this question
I am looking for a way to divide an int into whole numbers.
What I mean by this: if I have a number 30 and I want to divide this by 4, I want the output to be 8,8,7,7.
Is there a way in Java to do this?
Thanks in advance.
Sure, Java is turing complete and therefore allows you to implement any algorithm.
I assume that the difference between the resulting numbers should be at most one - you did not explicitly write this.
Try this:
final int input = 30;
final int numberOfPieces = 4;
final int quotient = input / numberOfPieces;
final int remainder = input % numberOfPieces;
int [] results = new int[numberOfPieces];
for( int i = 0; i < numberOfPieces; i++ ) {
results[i] = i < remainder ? quotient + 1 : quotient;
}
This code first calculates the integer quotient and then equally distributes the remainder to the first "pieces".
Since you don't want equal splits of the number, what you may do is :
Divide the number by how many ever parts you want.
Round() the result
Add up the rounded of number how many ever times required & check if sum is same, if not add or subtract 1 as necessary.
Eg: N = 150 , parts = 4
=> 37.5 , Round it round(37.5) => 38
Now, 38*4 = 152 and 152-150 = 2 so subtract 2 from a number and your answer is 38, 38, 38 & 36.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float number = 30.0f;
float parts = 4.0f;
float val = number / parts;
val = Math.round(val);
if (val * parts == number){
System.out.println("Numbers are:");
for (int i = 0; i < parts; i++)
System.out.println(val);
}
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for(int i = 0;i < parts - 1; i++)
System.out.println(val);
System.out.println(val - diff);
}
}
}
Output:
Numbers are:
8.0
8.0
8.0
6.0
If you want to equally share the difference in the above case then just replace the else part with this:
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for (int i = 0; i < parts - diff; i++)
System.out.println(val);
for (int i = 0; i < diff; i++)
System.out.println(val - 1);
}
Your output will be:
Numbers are:
8.0
8.0
7.0
7.0
Related
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I'm new to Java.
If you want to know what I'm trying to solve, check this: http://codeforces.com/problemset/problem/200/B
The two versions of the code, solve the same problem:
1-(for loop) version
public static void method() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double sum = 0;
for (int i = 0; i < n; i++)
sum += (sc.nextInt() / 100.0);
System.out.println(sum * 100.0 / n);
}
2-(while loop) version
public static void method() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double sum = 0;
while (n-- > 0) {
sum += (sc.nextInt() / 100.0);
}
System.out.println((sum * 100.0) / n);
}
===================================================
Here is the input for each of them:
3
50 50 100
Here is the output of each of them:
1-(for loop): 66.66666666666667
2-(while loop): -200.0
===================================================
Why the output differs?
n-- this will change the value of n and it will make it -1 at end.
so your sum will devide by -1 and you get -200 but in first solution n does not change and at end 200/3 = 66.6
it looks like you are decrementing n and then evaluating which will allow n to become negative
-- X = decrement X then evaluate
X -- = evaluate X then decrement X
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.
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 5 years ago.
Improve this question
I was solving problem 4 of ProjectEuler:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
I couldn't get it right. This is my code:
public static long reverseNumber(long number){
long reversed = 0;
while(number != 0) {
long digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return reversed;
}
long sum,finalSum=1,revSum;
for (int i=100;i<1000;i++){
for (int j=100;j<1000;j++){
sum=i*j;
revSum=reverseNumber(sum);
if (sum==revSum){
finalSum=sum;
}
}
}
System.out.println(finalSum);
This is some code I found online and it worked perfectly:
int maxPalin = -1;
for (int i = 100; i < 1000; i++) {
for (int j = 100; j < 1000; j++) {
int prod = i * j;
if (prod > maxPalin){
if (reverseNumber(prod)>maxPalin) {
maxPalin = prod;
}
}
}
}
System.out.println(Integer.toString(maxPalin));
But what's wrong with mine?
The goal is to find the max palindrome which is a product of two numbers between 100 and 999. The issue with your code is that you assume that last palindrome found would be the largest. This assumption is wrong.
For each palindrome you find, you should check if it's larger than the last palindrome you found before choosing it as a candidate for being the max palindrome.
BTW, the second snippet you posted is also incorrect, since it doesn't actually check that the current product is a palindrome (i.e. that prod==reverseNumber(prod)).
A correct implementation would be:
public static void maxp () {
int maxPalin = -1;
for (int i = 100; i < 1000; i++) {
for (int j = 100; j < 1000; j++) {
int prod = i * j;
if (reverseNumber(prod) == prod && prod > maxPalin) {
maxPalin = prod;
}
}
}
System.out.println(maxPalin);
}
Your code returns a palindrome that isn't the max palindrome (the product of 995 and 583) :
580085
The second snippet returns a number that isn't a palindrome at all:
980099
The correct answer is the product of 913 and 993:
906609
Your implementation didn't find it because you overwrote it with a palindrome found in a later iteration, that was a product of a higher i with a smaller j.
I am trying to create an app where the user has to memorize a random number (17 digits long) and then enter what she/he remembers.
After generating the number, how do I check how similar they are i.e. 10 of the digits match so it is 58% similar.
Lets say you compare this two strings:
String number1; // users number
String number2; // your number
Since you said both will be 17 digit long, no need to take in account different sizes (then you should go from the end):
int matches = 0;
for (int i = 0; i < number1.length(); i++) {
if (number1.substring(i, i + 1).equals(number2.substring(i, i + 1))) matches++;
}
Another approach would be with char arrays:
char[] charArray1 = number1.toCharArray();
char[] charArray2 = number2.toCharArray();
for (int i = 0; i < charArray1.length; i++) {
if (charArray1[i] == charArray2[i]) matches++;
}
Or by using Strings own array of chars (thanks #David Wallace):
for (int i = 0; i < charArray1.length; i++) {
if (number1.charAt(i) == number2.charAt(i)) matches++;
}
Now, you calculate procent:
double procent = matches / (number1.length() * 1d) * 100;
You must multiply with double value of 1, so it doesn't calculates with int, this will force it to deal with doubles.
you can use integer(or long) division and modulo to get the digits of an int.
See this java snippet:
int num1=1234;
int dig[]=new int[4];
dig[3]=num1 /1000;
dig[2]=(num1%1000)/100;
dig[1]=(num1%100) /10;
dig[0]=(num1%10) /1;
for(int i=0;i<4;i++){
System.out.println("dig"+i+" : "+dig[i]);
}
It will print:
dig0 : 4
dig1 : 3
dig2 : 2
dig3 : 1
I am working on a very simple spoj problem in which we have to take input N calculate its factorial then find out number of trailing zeros and display it some thing like
Sample Input:
6
3
60 // fact of 60 has 14 trailing zeros
100
1024
23456
8735373
Sample Output:
0
14
24
253
5861
2183837
so i have written a code which is working fine on my machine but when i am submitting it is giving me time limit error. i don't know how to make this code fast. So i want suggestions from you guys.
public class Factorial {
public static void main(String[] args) throws IOException {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
for (int i = 0; i < t; i++) {
Long num = Long.parseLong(bf.readLine());
BigInteger bd = BigInteger.valueOf(num);
System.out.println(countTrailinZeros(factorial(bd.toString())));
}
} catch (IllegalStateException e) {
return;
}
}
public static BigInteger factorial(String n) {
BigInteger x = BigInteger.valueOf(1);
for (long i = 1; i <= Integer.parseInt(n); i++) {
x = x.multiply(BigInteger.valueOf(i));
}
return x;
}
public static int countTrailinZeros(BigInteger bd) {
String s = bd.toString();
int glen = s.length();
s = s.replaceAll("[0.]*$", "");
int llen = s.length();
return glen - llen;
}
}
I have googled about some possible solutions and found out that lookup table may work i don't have much idea about this. I'd be very thankful if some can explain me about lookup table.
edit: Could it be java is too slow to solve this problem in given time? or in general it is not favorable to use java for competitive programing?
you dont need to calculate factorial to get number of trailing zeroes.
Solution :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int lines = Integer.parseInt(br.readLine());
int sum, N, p;
for (int i = 0; i < lines; i++) {
N = Integer.parseInt(br.readLine());
sum = 0;
p = 5;
while (N / p != 0) {
sum = sum + N / p;
p = p * 5;
}
System.out.println(sum);
}
}
}
Logic is :
The highest power of a prime number p in N! is given by
floor(N/p) + floor(N/p*p) + floor(N/p*p*p) ... so on till [floor(N/p^n) = 0]
so since number of ending zeroes is required , ans = min(max power of 2 in N!, max power of 5 in N!)
because zeroes appears on multiplication by ten and ten can be decomposed to 10 = (2 * 5).
It is fine to assume that max power of 5 in N! is always less than max power of 2 in N!.
as multiples of 2 occur more frequently than multiples of 5.
So problem reduces to finding max power of 5 in N! and hence the solution.
Example :
N = 5
max power of 5 in 5! = floor(5/5) + floor(5/25) => 1 + 0 => ans = 1
N = 100
max power of 5 in 100! = floor(100/5) + floor(100/25) + floor(100/125) => 20 + 4 + 0 => ans = 24
I have solved the same problem in spoj platform, you just have to divide the value by 5 until the value becomes less than 5. print all the result of the division and that's your output.
To solve this problem, consider prime factorization of N factorial:
N! = 2^a1 * 3^a2 * 5^a3 * .... where a1, a2, a3, ... >= 0
Since N! = N*(N-1)(N-2)..., multiples of 2 are more frequent than 5.
So, a1 >= a3 in this expansion.
Number of trailing zeros = how many times you can divide N! by 10.
Which implies, ans = min(a1, a3) based on the prime factorization given above.
Since we already proved a1 >= a3, hence ans = a3, i.e power of 5 in the prime factorization of N!.
There will be floor(N/5) numbers that will contribute to power of 5 atleast once.
There will be floor(N/25) numbers that will contribute to power of 5 atleast twice.
There will be floor(N/125) numbers that will contribute atleast thrice
and so on.
The total power of 5 = floor(N/5) + floor(N/25) + floor(N/125) + ...
Implementation of this formula in code is left as an exercise.