import java.util.Scanner;
class Factorial {
public static void main(String args[]) {
int n, c, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
For this code for finding the factorial of a number, I don't get the part where it says, "fact=fact*c".
I know it's because fact gets "updated" with a new multiplication factor of c, but do the numbers multiply?
Example: n=3 and c=1,2,3 and fact=1.. then would the process look like, (1*1) * (1*2) * (1*3)= 6?
The expression
fact = fact * c;
multiplies fact by c and stores the result in fact.
Thus the following happens when the code is run:
At the start , fact is 1.
On the first iteration it gets multiplied by 1 the result of which is 1.
On the second iteration it gets multiplied by 2 and becomes 2.
On the third iteration it gets multiplied by 3 and becomes 6.
On the fourth iteration it gets multiplied by 4 and becomes 24.
and so on.
You are right it works like this:
fact is 1 initially
loop when c = 1:
multiply c with fact i.e. 1 * 1
store the result back in fact i.e. fact = 1
loop when c = 2
multiply c with fact i.e. 1 * 2
store the result back in fact i.e. fact = 2
loop when c = 3
multiply c with fact i.e. 2 * 3
store the result back in fact i.e. fact = 6
Related
So I'm having some issues with code I'm writing for an assignment and it's kinda driving me crazy. It's my first semester and I've never done coding before, so I know I still have heaps to learn. Anyways, the issues:
I'm having two problems which could be related but I'm not 100% sure. I'm getting this error:
'Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 125 out of bounds for length 125.'
Which points to the following section of code (Commented on specific line):
public static String gradesDistn() {
String gradeDistn = "0";
//Sort the above letterGrade array
Arrays.sort(letterGrade);
//This loop counts each occurrence of an element in the letterGrade array.
for (int i = 0; i < letterGrade.length - 1; i++) {
int count = 0;
for(int j = i + 1; j < letterGrade.length; j++) {
if (letterGrade[i] == letterGrade[j])
count++;
System.out.println (gradeDistn = letterGrade[i] + ": " + count); //THIS IS THE ERROR LINE.
i += (count-1);
}
}
return gradeDistn;
I can post the full code if additional context is needed. Essentially I'm am trying to count the occurrences of each letter grade (A, B, C, D, E and F) which are stored in an array. Each occurrence is based off of another array which stores number marks and is randomly generated. So the results should look something like this:
A: 6
B: 10
C:20
D: 9
E: 3
F: 1
instead I'm getting (copied from console):
A: 1
A: 2
A: 3
A: 4
B: 5
B: 6
B: 7
B: 8
B: 9
B: 10
B: 11
C: 11
C: 11
D: 11
D: 11
F: 11
C: 20
D: 9
E: 3
F: 1
I've spent so long looking at these code and trying to make it work, I feel like I'm am blind to the potentially obvious issues with it. Any help on this 2 issues would be really appreciated!
Also of note: The assignment requires a bunch of super specific methods such as this so that can't be changed, addition classes can not be used etc.
For this answer, I'm going to put aside the question of ArrayIndexOutOfBoundsException and offer guidance on how to generate a frequency distribution.
You are going to want a set of counters. Each counter will represent a range of values. To start, you should decide what range each counter will represent. Too fine a resolution, and your frequency distribution will not be very useful. For example, if your data is 100 meter sprint times for high school boys, and each counter represents an interval of 1/10,000 of a second, unless your sample size is very large, your frequency distribution would have a lot of values of '1' and '0'. You might want to separate by 1/10 of a second, 1 second, or 2 seconds, depending on how much variation there is in the boys' times.
But, if your data is species of farm animals, it would be fine to have a separate counter for each possible value.
So, determine how many counters you will need. What is the range of possible values? How closely do you want to group them?
Next, you will want a means of linking a particular value to a particular counter. In some cases, a little math can be used. In other cases, an if ... else if ... chain or a switch block is useful.
For the first example, I want to analyze daily high temperatures. I decide to group by 10 degrees Fahrenheit. I could decide on 5 degrees, 7 degrees, or some other interval. It could even be irregular intervals. But, keeping it regular and going by 10 degrees makes the example easier to follow.
Having settled on grouping by 10 degrees, I next want to decide the maximum and minimum. I'll pick -19 as the coldest, and 119 as the hottest. But, I want to allow for occurrences outside of that range. So, to hold the count, I will want an array of 15 counters.
Next, I will want a means of "translating" a temperature measurement to an array index. I use the int variable k for that in the following code. To make it easier to follow, I broke the calculation into 4 lines and then used the result as a subscript:
public static int [] tempFreqDist (WeatherStats [] daily) {
int [] count = new int [15]; // java initializes to zeros
int k;
for (int dIdx = 0; dIdx < daily.length; ++ dIdx) {
k = daily [dIdx].getHighTemp();
k = Math.max (k,-20);
k = Math.min (k,120);
k = k/10 + 2;
count [k]++;
}
return count;
}
That's it! One loop, and no sorting.
We want to group temps of -20 and colder together, regardless of how far below -20. So, we use Math.max. Similarly, we group temps of 120 and hotter by using Math.min. Next, divide by our grouping factor, and adjust the result so the lowest has 0 for the subscript value.
So, the result is the elements of count correspond to the temperature ranges: 0 ➔ -20 and colder; 1 ➔ "teens" (10 to 19) below zero; 2 ➔ single digits below zero; 3 ➔ zero and single digits above; 4 ➔ teens above zero; 5 ➔ twenties, ..., 14 ➔ teens above 100; 14 ➔ 120 and above.
But, suppose the 'width' of categories was irregular? One possibility is that you could use a chain of if ... else:
int t = daily [dIdx].getHighTemp();
if (t <= -20) k = 0;
else if (t <= -13) k = 1;
else if (t <= 0) k = 2;
else if (t <= 15) k = 3;
else if (t <= 28) k = 4;
and so on.
Another example counts animals you might see on a farm.
You can do that with an if ... else if ... chain:
public int[] animalFD (String [] species) {
int [] count = new int [6];
// 0 ➔ cattle, 1 ➔ pig, 2 ➔ sheep,
// 3 ➔ goat, 4 ➔ duck, 5 ➔ horse
...
for (int m = 0; m < species.length; ++m) {
if (species[m].equals("cow") count[0]++;
else if (species[m].equals("pig") count [1]++;
else if ...
But, for something like this, I prefer switch to if ... else chain:
public static int [] animalFD (String [] species) {
int [] count = new int [6];
for (int m = 0; m < species.length; ++m) {
switch (letterGrade [m]) {
case "cow":
count[0]++;
break;
case "pig":
count [1]++;
break;
case "sheep":
count [2]++;
break;
case "goat":
count [3]++;
break;
...
Here is a "trick" you can use to easily convert a letter to an index. Recall that a char is essentially a integer primitive: You can do numeric calculations on it.
char letter;
int idx;
...
if (letter >= 'A' && letter <= 'Z') {
idx = letter - 'A'; // result is zero to 25
...
This takes advantage of the fact that the letters A to Z are consecutive in character set encoding. However, that isn't universal. EBCDIC, for example, has non-letter characters between I and J, and between R and S, IIRC.
The problem statement is :
Problem Statement-: Altaf has recently learned about number bases and is becoming fascinated.
Altaf learned that for bases greater than ten, new digit symbols need to be introduced, and that the convention is to use the first few letters of the English alphabet. For example, in base 16, the digits are 0123456789ABCDEF. Altaf thought that this is unsustainable; the English alphabet only has 26 letters, so this scheme can only work up to base 36. But this is no problem for Altaf, because Altaf is very creative and can just invent new digit symbols when she needs them. (Altaf is very creative.)
Altaf also noticed that in base two, all positive integers start with the digit 1! However, this is the only base where this is true. So naturally, Altaf wonders: Given some integer N, how many bases b are there such that the base-b representation of N starts with a 1?
Input Format :
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of one line containing a single integer N (in base ten).
Output Format :
For each test case, output a single line containing the number of bases b, or INFINITY if there are an infinite number of them.
Constraints:
1 <= T <= 10^5
0 <= N < 10^12
Sample Input
4
6
9
11
24
Sample Output:
4
7
8
14
Explanation:
In the first test case, 6 has a leading digit 1 in bases 2, 4, 5 and 6: 610 = 1102 = 124 = 115 = 106.
I trying this in java , But at some point my loop is not working it only takes the first value and after that it will come out of the loop!! Thank you
My code :
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long n,i,j,k,m;
long count=0,rem1,index;
long rem[];
rem = new long[(int)100];
int t = sc.nextInt();
for(i=1;i<=t;i++)
{
n = sc.nextInt();
j=2;
while(j<=n)
{
// for(j=2;j<=n;j++)
// {
index=0;
m = j;
while(n>0)
{
rem1 = n%m;
rem[(int)index++] = rem1;
n = (long) (n / m);
}
// for(k=index-1;k>=0;k--)
// {
if(rem[1]==1)
{
count++;
}
// }
j++;
}
System.out.println(count);
// }
}
}
}
I'm not sure I follow the logic in the loop (and, by your own admission, there's a problem there).
The logic of the loop (i.e., "how many bases represent the number N with a representation starting by 1"), can be greatly simplified.
The first step is finding the highest power of the base B required to represent the number N. This is given by logb(n), truncated to the nearest integer. Java doesn't have a built-in log function with a variable base, but you can get this result by calculating log(n)/log(b).
Then, you need to find the digit in this position. This can be calculated by dividing N by Bpower using integer division.
From there on, you just need to check if the result is 1, and if so, record it.
Put it all together and you'll end up with something like this:
private static int howManyBasesStartWithOne(int num) {
int count = 0;
for (int i = 2; i <= num; ++i) {
int highestBase = (int) (Math.log(num) / Math.log(i));
int leadingDigit = num / (int) Math.pow(i, highestBase);
if (leadingDigit == 1) {
++count;
}
}
return count;
}
I came across this codes for finding the GCD of an array of numbers from here
//Function to return gcd of a and b
static int gcd(int a, int b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
// Function to find gcd of array of
// numbers
static int findGCD(int arr[], int n) {
int result = arr[0];
for (int i = 1; i < n; i++) {
result = gcd(arr[i], result);
}
return result;
}
The method gcd uses a recursive call gcd(b % a, a). So how does this recursive call works? I know the basics of how a recursion works but I am a little confused on how the gcd method on this piece of code uses recursion. Can anyone please explain to me simply, how the gcd method works in this code?
Let's take two numbers 24 and 60, and you called the function as gcd(24, 60), then the function stack executes as follows,
gcd(24,60) => 60%24 = 12
gcd(24,12) => 12%24 = 12 (Switch happens)
gcd(12,24) => 24%12 = 0
gcd(0 ,12) => terminates
So switch that happens at step two is the important one because the call basically swaps two numbers, just like you do in an iterative way, think of it like shorthand way.
I could take the same example with 60 and 24 as the first call, then gcd(60,24) would execute as
gcd(60,24) => 24%60 = 24 (Switch happens)
gcd(24,60) => 60%24 = 12 and this follows the same pattern as the above
Here the switch happens because the functions send b%a to the next function as a and a to the function as b.
Given two numbers, 12 and 8:
gcd(12,8) calculates b%a = 12%8 = 4 and then calls gcd(4, 8). It does not return yet, because that last call is not completed yet.
gcd(4,8) calculates b%a = 8%4 = 0 and then calls gcd(0,4). That one does not return yet as well, because that call is active.
gcd(0,4) branches into the first if-statement and returns 4.
That defines the return value of gcd(4,8), so the pending call returns 4 as well.
That again defines the return value of gcd(12,8), so the final result is still 4.
The math behind it is also interesting.
I think the main question is: why can we reduce gcd(12,8) to gcd(4,8)?
We assume that there is any result g that can divide 12 without a remainder and 8 without a remainder.
We can split the 12 into g*n (4*3) and 8 into g*m (4*2).
Next, we can say 12-8 = gn-gm = g*(n-m) (4*(3-2)=4). Therefore g does not only divide 12 and 8 without remainder, but also 12-8 (4).
You can do that for even lower numbers: 12-8-8 = gn-gm-gm=g(n-m-m) (4*(3-2-2)=-4). And so on.
The same is true for larger numbers: 12+8 = gn+gm = g*(n+m) (4*(3+2)=20). And you can repeat that by adding 8 numerous times.
The smallest positive number you can get by this approch is 12%8, because you can subtract 8 from 12 for so many times until its remainder is left.
To help understand recursive methods it is often useful to place print statements in key locations so you can follow what is happening.
By calling the method with specifically chosen prime factors, it is easy to ensure a particular gcd.
In the example below, 3 is the only common factor so it will be the gcd of the two numbers.
public class RecursiveGCD {
public static void main(String[] args) {
System.out.println("GCD = " + gcd(2 * 3 * 4 * 4 * 5, 3 * 7 * 11));
}
public static int gcd(int a, int b) {
System.out.println("\nFinding gcd of a=" + a + " and b=" + b);
if (a == 0) {
System.out.println("a == 0 so returning b (gcd) = " + b);
return b;
}
System.out.println(
"Remainder non-zero, calling with gcd(b % a, a) = gcd(" + (b % a)
+ ", " + a + ").");
return gcd(b % a, a);
}
}
the question is "Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit."
public static void main(String[] args){
System.out.println(persistence(39));
//System.out.println(persistence(999));
}
public static int persistence(long n) {
long m = 1, r = n;
if (r / 10 == 0) {
return 0;
}
for(r = n; r!= 0; r /=10){
m *= r % 10;
}
//System.out.println(m);
return persistence(m) + 1;
}
I understand that the if statement is for when its finally a single digit and it'll return 0. If i could get an explanation on the m variable and what its there for. What the for loop does and when it returns persistence(m) why there is a + 1 on it.
The calculation will comes likes this .
let us understand the problem statement.
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
digit."
Say : 39
which is the number of times you must multiply the digits in num
until you reach a single digit.
So, we need to do like this to satisfy the above statement.
39 = 3*9 = 27 (1 time) - persistance(39)
27 = 2*7 = 14 (2rd time) - persistance(27)
14 = 1*4 = 4 (3rd time)- persistance(14)
So, according to the problem statement we come to the single digit.
you can take reference of the below, understand it .
why there is a + 1 on it.
to count the number of times the recursive function done the calculation.
As the title says, given a stock of integers 0-9, what is the last number I can write before I run out of some integer?
So if I'm given a stock of, say 10 for every number from 0 to 9, what is the last number I can write before I run out of some number. For example, with a stock of 2 I can write numbers 1 ... 10:
1 2 3 4 5 6 7 8 9 10
at this point my stock for ones is 0, and I cannot write 11.
Also note that if I was given a stock of 3, I could still write only numbers 1 ... 10, because 11 would cost me 2 ones, which would leave my stock for ones at -1.
What I have come up so far:
public class Numbers {
public static int numbers(int stock) {
int[] t = new int[10];
for (int k = 1; ; k++) {
int x = k;
while (x > 0) {
if (t[x % 10] == stock) return k-1;
t[x % 10]++;
x /= 10;
}
}
}
public static void main(String[] args) {
System.out.println(numbers(4));
}
}
With this I can get the correct answer for fairly big stock sizes. With a stock size of 10^6 the code completes in ~2 seconds, and with a stock of 10^7 numbers it takes a whole 27 seconds. This is not good enough, since I'm looking for a solution that can handle stock sizes of as big as 10^16, so I probably need a O(log(n)) solution.
This is a homework like assignment, so I didn't come here without wrestling with this pickle for quite some time. I have failed to come up with anything similiar by googling, and wolfram alpha doesn't recognize any kind of pattern this gives.
What I have concluded so far is that ones will allways run out first. I have no proof, but it is so.
Can anyone come up with any piece of advice? Thanks a lot.
EDIT:
I have come up with and implemented an efficient way of finding the cost of numbers 1...n thanks to btilly's pointers (see his post and comments below. also marked as a solution). I will elaborate this further after I have implemented the binary search for finding the last number you can write with the given stock later today.
EDIT 2: The Solution
I had completely forgotten about this post, so my apologies for not editing in my solution earlier. I won't copy the actual implementation, though.
My code for finding the cost of a number does the following:
First, let us choose a number, e.g. 9999. Now we will get the cost by summing the cost of each tens of digits like so:
9 9 9 9
^ ^ ^ ^
^ ^ ^ roof(9999 / 10^1) * 10^0 = 1000
^ ^ roof(9999 / 10^2) * 10^1 = 1000
^ roof(9999 / 10^3) * 10^2 = 1000
roof(9999 / 10^4) * 10^3 = 1000
Thus the cost for 9999 is 4000.
the same for 256:
2 5 6
^ ^ ^
^ ^ roof(256 / 10^1) * 10^0 = 26
^ roof(256 / 10^2) * 10^1 = 30
roof(256 / 10^3) * 10^2 = 100
Thus the cost for 256 is 156.
Implementing with this idea would make the program work only with numbers that have no digits 1 or 0, which is why further logic is needed. Let's call the method explained above C(n, d), where n is the number for which we are getting the cost for, and d is the d'th digit from n that we are currently working with. Let's also define a method D(n, d) that will return the d'th digit from n. Then we will apply the following logic:
sum = C(n, d)
if D(n, d) is 1:
for each k < d, k >= 0 :
sum -= ( 9 - D(n, k) ) * 10^(k-1);
else if D(n, d) is 0:
sum -= 10^(d-1)
With this the program will calculate the correct cost for a number efficiently. After this we simply apply a binary search for finding the number with the correct cost.
Step 1. Write an efficient function to calculate how much stock needs to be used to write all of the numbers up to N. (Hint: calculate everything that was used to write out the numbers in the last digit with a formula, and then use recursion to calculate everything that was used in the other digits.)
Step 2. Do a binary search to find the last number you can write with your amount of stock.
We can calculate the answer directly. A recursive formula can determine how much stock is needed to get from 1 to numbers that are powers of ten minus 1:
f(n, power, target){
if (power == target)
return 10 * n + power;
else
return f(10 * n + power, power * 10, target);
}
f(0,1,1) = 1 // a stock of 1 is needed for the numbers from 1 to 9
f(0,1,10) = 20 // a stock of 20 is needed for the numbers from 1 to 99
f(0,1,100) = 300 // a stock of 300 is needed for the numbers from 1 to 999
f(0,1,1000) = 4000 // a stock of 4000 is needed for the numbers from 1 to 9999
Where it gets complicated is accounting for the extra 1's needed when our calculation lands after the first multiple of any of the above coefficients; for example, on the second multiple of 10 (11-19) we need an extra 1 for each number.
JavaScript code:
function f(stock){
var cs = [0];
var p = 1;
function makeCoefficients(n,i){
n = 10*n + p;
if (n > stock){
return;
} else {
cs.push(n);
p *= 10;
makeCoefficients(n,i*10);
}
}
makeCoefficients(0,1);
var result = -1;
var numSndMul = 0;
var c;
while (stock > 0){
if (cs.length == 0){
return result;
}
c = cs.pop();
var mul = c + p * numSndMul;
if (stock >= mul){
stock -= mul;
result += p;
numSndMul++;
if (stock == 0){
return result;
}
}
var sndMul = c + p * numSndMul;
if (stock >= sndMul){
stock -= sndMul;
result += p;
numSndMul--;
if (stock == 0){
return result;
}
var numMul = Math.floor(stock / mul);
stock -= numMul * mul;
result += numMul * p;
}
p = Math.floor(p/10);
}
return result;
}
Output:
console.log(f(600));
1180
console.log(f(17654321));
16031415
console.log(f(2147483647));
1633388154