Write a program that calculates N! / K! for given N and K.in Java - overflow problem - overflow

import java.util.Scanner;
public class CalculateAgain {
public static void main (String[] Args) {
Scanner input = new Scanner(System.in);
long N = input.nextLong();
long K = input.nextLong();
double result = 1;
while ( N > K) {
result*=N;
N--;
}
System.out.printf("%.0f", result);
}
}
I am unable to print bigfactorial numbers. I have tried with the variable result as long but when I println it I get wrong result.
I have also tried to use BigDecimal but I cannot cast it to long or double.
I am quite a beginner - I have learned loops, arrays, conditional statements. I have no understanding of methods.

Use import java.math.BigInteger;
try this way, after scanner. Assuming I am using BigInteger, you can change as per your requirements.
int n = Integer.parseInt(scanner.nextLine());
int k = Integer.parseInt(scanner.nextLine());
BigInteger result = new BigInteger("1");
int range = n - k;
for (int i = range; i > 0; i--) {
result = result.multiply(new BigInteger(String.valueOf(n)));
n--;
}

Related

Understanding Big-O with a specific example

I am working on a rather simple question, to make sure that I understand these concepts.
The question is: there exists an array A of n elements, either being RED, WHITE, or BLUE. Rearrange the array such that all WHITE elements come before all BLUE elements, and all BLUE elements come before all RED elements. Construct an algorithm in O(n) time and O(1) space.
From my understanding, the pseudocode for the solution would be:
numW = numB = 0
for i = 0 to n:
if ARRAY[i] == WHITE:
numW++
else if ARRAY[i] == BLUE:
numB++
for i = 0 to n:
if numW > 0:
ARRAY[i] = WHITE
numW--
else if numB > 0:
ARRAY[i] = BLUE
numB--
else:
ARRAY[i] = RED
I believe it is O(n) because it runs through the loop twice and O(2n) is in O(n). I believe the space is O(1) because it is not dependent on the overall number of elements i.e. there will always be a count for each
Is my understanding correct?
If it's linear time, and your algorithm appears to be, then it's O(n) as you suspect. There's a great summary here: Big-O for Eight Year Olds?
Yes, your solution runs in O(n) time in O(1) space.
Below is my solution which also runs in O(n) time and O(1) space, but also works when we have references to objects, as #kenneth suggested in the comments.
import java.util.Arrays;
import java.util.Random;
import static java.lang.System.out;
class Color{
char c;
Color(char c){
this.c = c;
}
}
public class Solution {
private static void rearrangeColors(Color[] collection){
int ptr = 0;
// move all whites to the left
for(int i=0;i<collection.length;++i){
if(collection[i].c == 'W'){
swap(collection,ptr,i);
ptr++;
}
}
// move all blacks to the left after white
for(int i=ptr;i<collection.length;++i){
if(collection[i].c == 'B'){
swap(collection,ptr,i);
ptr++;
}
}
}
private static void swap(Color[] collection,int ptr1,int ptr2){
Color temp = collection[ptr1];
collection[ptr1] = collection[ptr2];
collection[ptr2] = temp;
}
private static void printColors(Color[] collection){
for(int i=0;i<collection.length;++i){
out.print(collection[i].c + ( i != collection.length - 1 ? "," : ""));
}
out.println();
}
public static void main(String[] args) {
// generate a random collection of 'Color' objects
Random r = new Random();
int array_length = r.nextInt(20) + 1;// to add 1 if in case 0 gets generated
Color[] collection = new Color[array_length];
char[] colors_domain = {'B','W','R'};
for(int i=0;i<collection.length;++i){
collection[i] = new Color(colors_domain[r.nextInt(3)]);
}
// print initial state
printColors(collection);
// rearrange them according to the criteria
rearrangeColors(collection);
// print final state
printColors(collection);
}
}
I won't say this is 100% correct, but a quick test case here did work. If anything, it shows the idea of being able to do it in one pass. Is it faster? Probably not. OP's answer I believe is still the best for this case.
#include <stdio.h>
char temp;
#define SWAP(a,b) { temp = a; a = b; b = temp;}
int main()
{
int n = 10;
char arr[] = "RWBRWBRWBR";
printf("%s\n", arr);
int white = 0;
for(int i=0; i<n; i++)
{
if(arr[i] == 'B')
{
SWAP(arr[i], arr[n-1]);
i--; n--;
}
else if(arr[i] == 'R')
{
SWAP(arr[i], arr[white]);
white++;
}
}
printf("%s\n", arr);
}

Factorial of factorial of a number

How can the factorial of a factorial of a number be efficiently computed.
Example:For 3 => (3!)! = (6)! = 720
The brute force way would be to simply call factorial twice using a simple for loop but can it be done better.
for(i=1;i<=n;i++)
fact=fact*i;
Edit: Need the result as ((n!)!)MOD 10^m, where m is an integer and 0<=m<=19
Note that result is 0 for n >=5 (5!!=120! has more than 19 zeros at the end), and result for smaller values it is easy to calculate.
Since ab mod n ≣ (a mod n)(b mod n), you can use the brute force algorithm, dividing by 10m after each multiplication. If the product ever equals 0, you can stop.
here i am using PHP.I think It help You
<?php
function double_factorial ($n)
{
if($n <= 1)
{
return 1;
}
else
{
$fat1=$n * factorial($n - 1);
return $fat1 * factorial($fat1 - 1);
}
}
echo double_factorial(3);
?>
1.For standard integer types
I agree with MBo
I would prefer table of precomputed values
2.For bigints
what about using fast factorial computation instead of O(N) loops?
here is one of mine ...
https://stackoverflow.com/a/18333853/2521214
The following code has been tested and works very well.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Factorial of six is :" + manipulator.factorial(16));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
}
}
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
int result = Factorial(input);
System.out.println(result);
scanner.close();
}
private static int Factorial(int input) {
int m = 1;
if (input < 0) {
return 0;
} else if (input > 0) {
m = input * Factorial(input - 1);
}
return m;
}
}

Longest Collatz Sequence

While doing my Java homework which is to implement the Collatz Conjecture, I thought of a different objective which is to find the longest Collatz sequence. My program counts the steps as follows:
public class Collatz {
static int count = 0;
static void bilgi (int n){
int result = n;
System.out.println("Result: "+result+ " Step: "+count);
if (result <= 1) {
result = 1;
} else if (result%2 == 0){
result = result/2;
count = count + 1;
bilgi(result);
} else {
result = (result*3)+1;
count = count + 1;
bilgi(result);
}
}
public static void main(String[] args) {
bilgi(27);
}
}
I want to find the highest step count.
static int bilgi(int n) {
int result = n;
if (result <= 1) return 1;
if (result % 2 == 0) return 1+bilgi(result/2);
return 1+bilgi(3*result+1);
}
Then you collect the results of bilgi(i) calls and select maximal.
The longest progression for any initial starting number less than 100 million is 63,728,127, which has 949 steps. For starting numbers less than 1 billion it is 670,617,279, with 986 steps, and for numbers less than 10 billion it is 9,780,657,630, with 1132 steps
source: http://en.wikipedia.org/wiki/Collatz_conjecture
If you're looking for max between 1 and 100 you could replace:
public static void main(String[] args) {
bilgi(27);
}
with :
public static void main(String[] args) {
static int maxcountsofar = 0;
static int start = 0;
static int thisone = 0;
for (int iloop = 1; iloop <= 100; iloop++)
{
thisone = bilgi(iloop);
if (thisone > maxcountsofar)//if this one is bigger than the highest count so far then
{
start = iloop;//save this information as best so far
maxcountsofar = thisone;
}
}
System.out.println("Result: " + start.Tostring() + " Step: " + maxcountsofar.Tostring() );
//I know this is a really old post but it looked like fun.
}
/*
also, take the println() out of the bilgi() function, it would generate a line for each step encountered which would be worthless and extremely time consuming.
Use Vesper's bigli() because it's much faster than yours.
*/
I know this is an old question, but I was just solving it and I would suggest for anyone doing this, just using an arraylist and getting the .size(), I did it that way, because I wanted to see the values as well.

Divisibilty of binomial coefficient(nCk) with prime number(P) for large n and k

In mathematics, binomial coefficients are a family of positive integers that occur as coefficients in the binomial theorem. nCk denotes the number of ways of choosing k objects from n different objects.
However when n and k are too large, we often save them after modulo operation by a prime number P. Please calculate how many binomial coefficients of n become to 0 after modulo by P.
Input
The first of input is an integer T, the number of test cases.
Each of the following T lines contains 2 integers, n and prime P.
Output
For each test case, output a line contains the number of nCk (0<=k<=n) each of which after modulo operation by P is 0.
Sample Input
3
2 2
3 2
4 3
Sample Output
1
0
1
Since the constraints are very big, dynamic programming will not work. All I want is an idea.
This is a problem about math.
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Solution{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int T=Integer.parseInt(scan.nextLine());
int i,j;
long p;
long y;
int[] digit=new int[501];
int[] odigit=new int[501];
int[] res=new int[501];
int[] ans=new int[501];
while(0!=(T--)){
String[] line=scan.nextLine().split(" ");
p=Integer.parseInt(line[1]);
for(i=0;i<line[0].length();i++)
digit[i+1]=odigit[i]=(line[0].charAt(i))-48;
digit[0]=odigit[0]=line[0].length()+1;
//基转换
//进制转换,10进制转换成p进制
res[0]=0;
while(digit[0]>1){
y=0;i=1;
ans[0]=digit[0];
while(i<digit[0]){
y=y*10+digit[i];
ans[i++]=(int)((double)y/(double)p);
y%=p;
}
res[++res[0]]=(int)y;
i=1;
while(i<ans[0]&&ans[i]==0)
i++;
digit[0]=1;
for(j=i;j<ans[0];j++)
digit[digit[0]++]=ans[j];
}
res[0]++;
//大数相乘
BigInteger odata=new BigInteger(line[0]);
BigInteger pdata=new BigInteger("1");
for(i=1;i<res[0];i++)
pdata=pdata.multiply(new BigInteger((res[i]+1)+""));
odata=odata.subtract(pdata).add(new BigInteger("1"));
System.out.println(odata.toString());
}
}
}
EDIT (code shorten by nhahtdh):
import java.math.BigInteger;
import java.util.*;
class Solution {
// Get the base b intepretation of n
private static ArrayList<Integer> toBase(BigInteger n, BigInteger b) {
ArrayList<Integer> out = new ArrayList<Integer>();
while (!n.equals(BigInteger.ZERO)) {
out.add(n.mod(b).intValue());
n = n.divide(b);
}
return out;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
while((T--) > 0){
BigInteger n = scan.nextBigInteger();
BigInteger p = scan.nextBigInteger();
ArrayList<Integer> res = toBase(n, p);
BigInteger pdata = BigInteger.ONE;
for (int i: res) {
pdata = pdata.multiply(BigInteger.valueOf(i + 1));
}
BigInteger output = n.subtract(pdata).add(BigInteger.ONE);
System.out.println(output);
}
}
}
quoted from the Lucas' theorem page:
A binomial coefficient \tbinom{m}{n} is divisible by a prime p if and
only if at least one of the base p digits of n is greater than the
corresponding digit of m.

search tree in scala

I'm trying to put my first steps into Scala, and to practice I took a look at the google code jam storecredit excersize. I tried it in java first, which went well enough, and now I'm trying to port it to Scala. Now with the java collections framework, I could try to do a straight syntax conversion, but I'd end up writing java in scala, and that kind of defeats the purpose. In my Java implementation, I have a PriorityQueue that I empty into a Deque, and pop the ends off untill we have bingo. This all uses mutable collections, which give me the feeling is very 'un-scala'. What I think would be a more functional approach is to construct a datastructure that can be traversed both from highest to lowest, and from lowest to highest. Am I on the right path? Are there any suitable datastructures supplied in the Scala libraries, or should I roll my own here?
EDIT: full code of the much simpler version in Java. It should run in O(max(credit,inputchars)) and has become:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class StoreCredit {
private static BufferedReader in;
public static void main(String[] args) {
in = new BufferedReader(new InputStreamReader(System.in));
try {
int numCases = Integer.parseInt(in.readLine());
for (int i = 0; i < numCases; i++) {
solveCase(i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void solveCase(int casenum) throws NumberFormatException,
IOException {
int credit = Integer.parseInt(in.readLine());
int numItems = Integer.parseInt(in.readLine());
int itemnumber = 0;
int[] item_numbers_by_price = new int[credit];
Arrays.fill(item_numbers_by_price, -1); // makes this O(max(credit,
// items)) instead of O(items)
int[] read_prices = readItems();
while (itemnumber < numItems) {
int next_price = read_prices[itemnumber];
if (next_price <= credit) {
if (item_numbers_by_price[credit - next_price] >= 0) {
// Bingo! DinoDNA!
printResult(new int[] {
item_numbers_by_price[credit - next_price],
itemnumber }, casenum);
break;
}
item_numbers_by_price[next_price] = itemnumber;
}
itemnumber++;
}
}
private static int[] readItems() throws IOException {
String line = in.readLine();
String[] items = line.split(" "); // uh-oh, now it's O(max(credit,
// inputchars))
int[] result = new int[items.length];
for (int i = 0; i < items.length; i++) {
result[i] = Integer.parseInt(items[i]);
}
return result;
}
private static void printResult(int[] result, int casenum) {
int one;
int two;
if (result[0] > result[1]) {
one = result[1];
two = result[0];
} else {
one = result[0];
two = result[1];
}
one++;
two++;
System.out.println(String.format("Case #%d: %d %d", casenum + 1, one,
two));
}
}
I'm wondering what you are trying to accomplish using sophisticated data structures such as PriorityQueue and Deque for a problem such as this. It can be solved with a pair of nested loops:
for {
i <- 2 to I
j <- 1 until i
if i != j && P(i-1) + P(j - 1) == C
} println("Case #%d: %d %d" format (n, j, i))
Worse than linear, better than quadratic. Since the items are not sorted, and sorting them would require O(nlogn), you can't do much better than this -- as far as I can see.
Actually, having said all that, I now have figured a way to do it in linear time. The trick is that, for every number p you find, you know what its complement is: C - p. I expect there are a few ways to explore that -- I have so far thought of two.
One way is to build a map with O(n) characteristics, such as a bitmap or a hash map. For each element, make it point to its index. One then only has to find an element for which its complement also has an entry in the map. Trivially, this could be as easily as this:
val PM = P.zipWithIndex.toMap
val (p, i) = PM find { case (p, i) => PM isDefinedAt C - p }
val j = PM(C - p)
However, that won't work if the number is equal to its complement. In other words, if there are two p such that p + p == C. There are quite a few such cases in the examples. One could then test for that condition, and then just use indexOf and lastIndexOf -- except that it is possible that there is only one p such that p + p == C, in which case that wouldn't be the answer either.
So I ended with something more complex, that tests the existence of the complement at the same time the map is being built. Here's the full solution:
import scala.io.Source
object StoreCredit3 extends App {
val source = if (args.size > 0) Source fromFile args(0) else Source.stdin
val input = source getLines ()
val N = input.next.toInt
1 to N foreach { n =>
val C = input.next.toInt
val I = input.next.toInt
val Ps = input.next split ' ' map (_.toInt)
val (_, Some((p1, p2))) = Ps.zipWithIndex.foldLeft((Map[Int, Int](), None: Option[(Int, Int)])) {
case ((map, None), (p, i)) =>
if (map isDefinedAt C - p) map -> Some(map(C - p) -> (i + 1))
else (map updated (p, i + 1), None)
case (answer, _) => answer
}
println("Case #%d: %d %d" format (n, p1, p2))
}
}

Resources