so I have this problem where finding the percentage doesn't work and I really don't know why,so my assignment is to find the number of candidates for election and the number of electors and at the end it should show the percentage of the votes example if there are 3 candidates and 6 electors and 1st candidate gets 3 votes,2nd gets 2 votes, and the 3rd gets 1 vote, it should show : 50.00%,33.33%,16.67%.
Below is my code, it gets right the number of votes but when it comes to percentage it just shows 0.0% in all cases.I hope you guys can help me out.
import java.util.Scanner;
public class ElectionPercentage {
public static void main(String[]args){
//https://acm.timus.ru/problem.aspx?space=1&num=1263
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many candidates are : ");
int candidates = sc.nextInt();
int [] allCandidates = new int[candidates];
int startingCandidate = 1;
for(int i = 0; i < candidates;i++){
allCandidates[i] = startingCandidate++; //now value of the first element will be 1 and so on.
}
//for testing System.out.println(Arrays.toString(allCandidates));
System.out.println("enter the number of electors : ");
int electors = sc.nextInt();
int [] allVotes = new int[electors];
for(int i =0;i < electors;i++){
System.out.println("for which candidate has the elector voted for :");
int vote = sc.nextInt();
allVotes[i] = vote; //storing all electors in array
}
System.out.println();
int countVotes = 0;
double percentage;
for(int i = 0;i<allCandidates.length;i++){
for(int k = 0; k < allVotes.length;k++){
if(allCandidates[i]==allVotes[k]){
countVotes++;
}
}
System.out.println("Candidate "+allCandidates[i]+" has : "+countVotes+" votes.");
percentage = ((double)(countVotes/6)*100);
System.out.println(percentage+"%");
countVotes = 0;
}
}
}
countVotes is an int 6 is also an int. Thus, (countVotes/6) which is in your code, near the end, is integer division. 11/6 in integer division is 1. 5/6 is 0. It rounds by lopping off all decimals. That's probably not what you want, especially because you try to cast it to double afterwards.
You're casting the wrong thing. But you don't even need the cast at all; if either side is double, the whole thing becomes double division. So, instead of: percentage = ((double)(countVotes/6)*100); try percentage = 100.0 * countVotes / 6.0;
Also, presumably, that 6 should really be a variable that counts total # of votes, no? i.e. electors, so: percentage = 100.0 * countVotes / electors;
The fact that we kick off the math with 100.0 means it'll be double math all the way down.
countVotes is an int. When you do (double)(countVotes/6), (countVotes/6) happens first. This evaluates to 0 since both are int. To fix this, change 6 to 6.0.
(double)(countVotes/6.0)*100
In which case, the cast to double is no longer needed.
(countVotes/6.0)*100
Related
This program is supposed to print the numbers (indiviual digits) in a number
`
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int number = sc.nextInt();
int Size = 0;
String Conversion = Integer.toString(number);
Size = Conversion.length();
int n = 0;
while (n <= Size){
int d = number%10;
int power = Size - 2;
number = (number/(10^(power)));
System.out.println(d);
n += 1;
}
}
}
`
Really Appreciate for Anyone for Took time to help me.
Thanks
For some reason I get
1
9
3.
instead of
1
3
4
using the debugger gives me some hint, Specifically this block `
number = (number/(10^(power)));
`
for second iteration the value is +4 than expected, 3.
for third Its okay.
changing and adding +4 on that block gives
1
3
7
4
Found it !!
Credit OH GOD SPIDERS, tkausl
Solution 1 : Instead of using carrot characters in
number = (number/(10^(power)));
use Math.pow function.
Solution 2 :
Don't use (number/(10^(power))
instead just divide by 10
I have spent a couple of hours struggling with this problem and I just can't figure out why it doesn't work. Basically, the question is to find the thirteen consecutive digits that have the greatest sum. If I modify it to look for four digits or five digits, it gets the correct answer, but when it looks for thirteen I get 2091059712, which is not correct. I am pretty new to coding, and am completely at a loss for what could be wrong.
// this is the 1000 digit number
String big = "73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843"+
"85861560789112949495459501737958331952853208805511"+
"12540698747158523863050715693290963295227443043557"+
"66896648950445244523161731856403098711121722383113"+
"62229893423380308135336276614282806444486645238749"+
"30358907296290491560440772390713810515859307960866"+
"70172427121883998797908792274921901699720888093776"+
"65727333001053367881220235421809751254540594752243"+
"52584907711670556013604839586446706324415722155397"+
"53697817977846174064955149290862569321978468622482"+
"83972241375657056057490261407972968652414535100474"+
"82166370484403199890008895243450658541227588666881"+
"16427171479924442928230863465674813919123162824586"+
"17866458359124566529476545682848912883142607690042"+
"24219022671055626321111109370544217506941658960408"+
"07198403850962455444362981230987879927244284909188"+
"84580156166097919133875499200524063689912560717606"+
"05886116467109405077541002256983155200055935729725"+
"71636269561882670428252483600823257530420752963450";
ArrayList<Integer> nums = new ArrayList<Integer>();
int counter = 0;
for (counter = 0; counter<988; counter++) {
String str = big.substring (counter,counter+13);
// creates a substring thirteen digits long
Integer product = 1;
for (int o=0; o<13; o++) {
String num = Character.toString(str.charAt(o));
Integer numb = Integer.parseInt(num);
// Turns each digit into an integer and then multiplies them together
product = product*numb;
}
nums.add(product);
}
//finds biggest number
int bignum = 0;
for (Integer num : nums) {
if (num > bignum) {
bignum = num;
}
}
Any help would be greatly appreciated. Thanks.
Change all your Integers to Longs, your only problem is integer storage.
You need to change your numb and bignum to Longs instead of Ints, if that donsen't work then you can change them to BigIntegers.
I am really hoping you can help me out. I am completely lost in my assignemnt and I have been in touch with my instructor, but I still do not understand how to approach my problem. The assignment states I need:
Current Maximum of all generated random numbers so far.
(Utilize Math class to determine current Max)
Current Minimum of all generated random numbers so far.
(Utilize Math class to determine current Min)
I know I need these where I currently have Math.max & Math.min at the lower end of my code. I just am clueless on how to implement it and what the numbers represent.
import java.util.Scanner;
public class CLASS {
public static void main(String[] args) {
Scanner stdln = new Scanner(System.in);
final String HEADING_STR = "%-15s%-15s%-15s%-15s%-15s%-15s\n";
final String DATA_STR = "%-15s%-15.0f%-15s%-15s%-15s%-15s\n";
String maxRandomNumberStr; // The maximum random number to be computed (an integer to be parsed)
String amountRandomNumbersStr; // The amount of random numbers to be generated (an integer to be parsed)
int maxRandomNumber; // the integer of maxRandomNumberStr
int amountRandomNumbers; // the integer of amountRandomNumbersStr
int round = 0; // the first round
//int theMax = 0; // how to use?
//int theMin = 0; // how to use?
System.out.print("Please enter the maximum random number to be used: ");
maxRandomNumberStr = stdln.nextLine();
maxRandomNumber = Integer.parseInt(maxRandomNumberStr);
System.out.print("Please enter the number of rounds: ");
amountRandomNumbersStr = stdln.nextLine();
amountRandomNumbers = Integer.parseInt(amountRandomNumbersStr);
System.out.printf (HEADING_STR, "Round", "Round #", "Curr Max", "Curr Min", "Curr Total", "Curr Avg");
for (int i=1; i<=amountRandomNumbers; i++) {
System.out.printf(DATA_STR, round += 1, (Math.random()*(maxRandomNumber)), Math.max(?,?), Math.min(?,?), "1", "1"); // the "1"s are placeholders
}
} // end main
} // end CLASS
If I am understanding your problem correctly I think your input for Math.max() and .min() would be the newest random number being compared to the old min/max. Please see the Math class documentation here: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
I think you would need to always save any new maximum/minimum variables and compare them to the new random number each time.
int theMax = 0;
theMax = Math.max(newRandomNumber, theMax);
This will assign theMax to be the highest of the two numbers.
You can do the same for min.
Good luck.
If you're using Java 8, you ca do it easily with a Stream.
Stream.of(random1, random2, ...).max();
Stream.of(random1, random2, ...).min();
Stream.of(random1, random2, ...).avg();
It was asked to find a way to check whether a number is in the Fibonacci Sequence or not.
The constraints are
1≤T≤10^5
1≤N≤10^10
where the T is the number of test cases,
and N is the given number, the Fibonacci candidate to be tested.
I wrote it the following using the fact a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0 ; i < n; i++){
int cand = sc.nextInt();
if(cand < 0){System.out.println("IsNotFibo"); return; }
int aTest =(5 * (cand *cand)) + 4;
int bTest = (5 * (cand *cand)) - 4;
int sqrt1 = (int)Math.sqrt(aTest);// Taking square root of aTest, taking into account only the integer part.
int sqrt2 = (int)Math.sqrt(bTest);// Taking square root of bTest, taking into account only the integer part.
if((sqrt1 * sqrt1 == aTest)||(sqrt2 * sqrt2 == bTest)){
System.out.println("IsFibo");
}else{
System.out.println("IsNotFibo");
}
}
}
}
But its not clearing all the test cases? What bug fixes I can do ?
A much simpler solution is based on the fact that there are only 49 Fibonacci numbers below 10^10.
Precompute them and store them in an array or hash table for existency checks.
The runtime complexity will be O(log N + T):
Set<Long> nums = new HashSet<>();
long a = 1, b = 2;
while (a <= 10000000000L) {
nums.add(a);
long c = a + b;
a = b;
b = c;
}
// then for each query, use nums.contains() to check for Fibonacci-ness
If you want to go down the perfect square route, you might want to use arbitrary-precision arithmetics:
// find ceil(sqrt(n)) in O(log n) steps
BigInteger ceilSqrt(BigInteger n) {
// use binary search to find smallest x with x^2 >= n
BigInteger lo = BigInteger.valueOf(1),
hi = BigInteger.valueOf(n);
while (lo.compareTo(hi) < 0) {
BigInteger mid = lo.add(hi).divide(2);
if (mid.multiply(mid).compareTo(x) >= 0)
hi = mid;
else
lo = mid.add(BigInteger.ONE);
}
return lo;
}
// checks if n is a perfect square
boolean isPerfectSquare(BigInteger n) {
BigInteger x = ceilSqrt(n);
return x.multiply(x).equals(n);
}
Your tests for perfect squares involve floating point calculations. That is liable to give you incorrect answers because floating point calculations typically give you inaccurate results. (Floating point is at best an approximate to Real numbers.)
In this case sqrt(n*n) might give you n - epsilon for some small epsilon and (int) sqrt(n*n) would then be n - 1 instead of the expected n.
Restructure your code so that the tests are performed using integer arithmetic. But note that N < 1010 means that N2 < 1020. That is bigger than a long ... so you will need to use ...
UPDATE
There is more to it than this. First, Math.sqrt(double) is guaranteed to give you a double result that is rounded to the closest double value to the true square root. So you might think we are in the clear (as it were).
But the problem is that N multiplied by N has up to 20 significant digits ... which is more than can be represented when you widen the number to a double in order to make the sqrt call. (A double has 15.95 decimal digits of precision, according to Wikipedia.)
On top of that, the code as written does this:
int cand = sc.nextInt();
int aTest = (5 * (cand * cand)) + 4;
For large values of cand, that is liable to overflow. And it will even overflow if you use long instead of int ... given that the cand values may be up to 10^10. (A long can represent numbers up to +9,223,372,036,854,775,807 ... which is less than 1020.) And then we have to multiply N2 by 5.
In summary, while the code should work for small candidates, for really large ones it could either break when you attempt to read the candidate (as an int) or it could give the wrong answer due to integer overflow (as a long).
Fixing this requires a significant rethink. (Or deeper analysis than I have done to show that the computational hazards don't result in an incorrect answer for any large N in the range of possible inputs.)
According to this link a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square so you can basically do this check.
Hope this helps :)
Use binary search and the Fibonacci Q-matrix for a O((log n)^2) solution per test case if you use exponentiation by squaring.
Your solution does not work because it involves rounding floating point square roots of large numbers (potentially large enough not to even fit in a long), which sometimes will not be exact.
The binary search will work like this: find Q^m: if the m-th Fibonacci number is larger than yours, set right = m, if it is equal return true, else set left = m + 1.
As it was correctly said, sqrt could be rounded down. So:
Even if you use long instead of int, it has 18 digits.
even if you use Math.round(), not simply (int) or (long). Notice, your function wouldn't work correctly even on small numbers because of that.
double have 14 digits, long has 18, so you can't work with squares, you need 20 digits.
BigInteger and BigDecimal have no sqrt() function.
So, you have three ways:
write your own sqrt for BigInteger.
check all numbers around the found unprecise double sqrt() for being a real sqrt. That means also working with numbers and their errors simultaneously. (it's horror!)
count all Fibonacci numbers under 10^10 and compare against them.
The last variant is by far the simplest one.
Looks like to me the for-loop doesn't make any sense ?
When you remove the for-loop for me the program works as advertised:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cand = sc.nextInt();
if(cand < 0){System.out.println("IsNotFibo"); return; }
int aTest = 5 * cand *cand + 4;
int bTest = 5 * cand *cand - 4;
int sqrt1 = (int)Math.sqrt(aTest);
int sqrt2 = (int)Math.sqrt(bTest);
if((sqrt1 * sqrt1 == aTest)||(sqrt2 * sqrt2 == bTest)){
System.out.println("IsFibo");
}else{
System.out.println("IsNotFibo");
}
}
}
You only need to test for a given candidate, yes? What is the for loop accomplishing? Could the results of the loop be throwing your testing program off?
Also, there is a missing } in the code. It will not run as posted without adding another } at the end, after which it runs fine for the following input:
10 1 2 3 4 5 6 7 8 9 10
IsFibo
IsFibo
IsFibo
IsNotFibo
IsFibo
IsNotFibo
IsNotFibo
IsFibo
IsNotFibo
IsNotFibo
Taking into account all the above suggestions I wrote the following which passed all test cases
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long[] fib = new long[52];
Set<Long> fibSet = new HashSet<>(52);
fib[0] = 0L;
fib[1] = 1L;
for(int i = 2; i < 52; i++){
fib[i] = fib[i-1] + fib[i - 2];
fibSet.add(fib[i]);
}
int n = sc.nextInt();
long cand;
for(int i = 0; i < n; i++){
cand = sc.nextLong();
if(cand < 0){System.out.println("IsNotFibo");continue;}
if(fibSet.contains(cand)){
System.out.println("IsFibo");
}else{
System.out.println("IsNotFibo");
}
}
}
}
I wanted to be on the safer side hence I choose 52 as the number of elements in the Fibonacci sequence under consideration.
This is my code
import java.util.*;
import java.io.*;
public class eCheck10A
{
public static void main(String[] args)
{
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter your integers");
out.println("Negative = sentinel");
List<Integer> aList = new ArrayList<Integer>();
for (int n1 = in.nextInt(); n1 > 0; n1 = in.nextInt())
{
if(n1 < 0)
{
break;
}
}
}
}
if i want to take all the numbers that I enter for n1, and average them out, how do i refer to all these numbers? I am going to put them in the IF statement, so if a negative number is entered, the program stops and posts their average.
This is the pseudocode you need to do this task (pseudo-code since it looks suspiciously like homework/classwork and you'll become a better developer if you nut out the implementation yourself).
Because you don't need the numbers themselves to work out the average, there's no point in storing them. The average is defined as the sum of all numbers divided by their count, so that's all you need to remember. Something like this should suffice:
total = 0
count = 0
n1 = get_next_number()
while n1 >= 0:
total = total + n1
count = count + 1
n1 = get_next_number()
if count == 0:
print "No numbers were entered.
else:
print "Average is ", (total / count)
A couple of other points I'll mention. As it stands now, your for statement will exit at the first non-positive number (<= 0), making the if superfluous.
In addition, you probably want any zeros to be included in the average: the average of {1,2,3} = 2 is not the same as the average of {1,2,3,0,0,0} = 1.
You can do this in the for statement itself with something like:
for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt())
and then you don't need the if/break bit inside the loop at all, similar to my provided pseudo-code.
An outline of what you will need to do: Create a variable sum to add up all of the values and create another variable called count that will be used to store the number of non-negative numbers in your list, aList. Then divide the sum by the count to find the average.
Another way to do running average is:
new_average = old_average + (new_number - old_average ) / count
If you ever hit max for a variable type, you would appreciate this formula.