Co Prime Monte Carlo Simulation - java

Im trying to create a program to get the probability that 2 numbers are Coprime.I think my algorithm is right but I'm getting runtime errors and I can't see why.
`
import java.util.*;
import java.util.Random;
public class coPrimeMonteCarlo
{
public static void main(String[]args)
{
Scanner s1 = new Scanner(System.in);
Random rand = new Random();
double total = 0;
double totalNum = 1000000;
for(int i=0;i<totalNum;i++)
{
int a = rand.nextInt();
int b = rand.nextInt();
if(isCoPrime(a,b)==1)
{
total++;
};
}
System.out.println(total/totalNum);
}
public static int isCoPrime(int a, int b)
{
if(a==b)
{
return a;
}
else if((a == 0 || b == 0))
{
return 0;
}
else if(a>b)
{
return isCoPrime(a-b,b);
}
return isCoPrime(a,b-a);
}
}
`
Output is
at coPrimeMonteCarlo.isCoPrime(coPrimeMonteCarlo.java:35)
at coPrimeMonteCarlo.isCoPrime(coPrimeMonteCarlo.java:35)
Tried Running but got that output.

Related

Java program not asking for input when ran, what did I do wrong?

I'm trying to create a code where the user inputs a number, and the program returns whether the number is prime or not. This is my first code in Java, so I'm still learning! The code compiles but when I run it, it doesn't have an option to input.
import java.util.Scanner;
public class Prime {
public void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int number = reader.nextInt();
if (isPrime(number) == true)
{
System.out.println(number+"is a prime number");
}
else
{
System.out.print(number+"is not a prime number");
}
}
public boolean isPrime(int number)
{
int counter = 0;
boolean result = true;
for (int n = 2; n <= 9; n++) {
if (number % n == 0 && n != number) {
counter = 1;
} else {
counter = 2;
}
if (counter == 1){
result = true;
}
else result = false;
}
return (result);
}
}
The issue here is regarding the main method which is missing the static keyword, so there is no app entry without that.
Please change the main method from
public void main(String[] args)
To
public static void main(String[] args)
Also, add static to the isPrime method in order to everything work.
This problem arised because of no Entry point was found by the java compiler
Code Snippet
Run Code Here
import java.util.Scanner;
public class Prime {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int number = reader.nextInt();
if (isPrime(number) == true)
{
System.out.println(number+"is a prime number");
}
else
{
System.out.print(number+"is not a prime number");
}
}
static public boolean isPrime(int number)
{
int counter = 0;
boolean result = true;
for (int n = 2; n <= 9; n++) {
if (number % n == 0 && n != number) {
counter = 1;
} else {
counter = 2;
}
if (counter == 1){
result = true;
}
else result = false;
}
return (result);
}
}

how to return in a recurssive fn in java

Actually my aim is to find the super no for eg i will be given 2 values n,k where n=148 and k =3 so i have to form p = 148148148 then add digits of p until i get a single no (ans = 3) this is what i have tried.......
import java.util.*;
public class RecurrsiveDigitSum {
public int check(int n) {
int s = 0;
int d;
while(n>0) {
d = n%10;
s = s+d;
n = n/10;
System.out.println(s);
}
if(s/10 !=0){
check(s);
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int sum;
RecurrsiveDigitSum obj = new RecurrsiveDigitSum();
sum = obj.check(n);
System.out.println(sum);
sum = sum * k;
System.out.println(sum);
int s1 = obj.check(sum);
System.out.println(s1);
}
}
but the problem here is that even if my s = 4 finally its just returning the first value of s that has been found so pls help me friends
you must put return before recursive calling.
if(s/10 !=0){
return check(s);
}
If you don't put it, the result of calling function will be loss and the result of s will be returned instead of check(s).
I've improved your solution little bit.
public int check(int n) {
int s = 0;
while(n>0) {
s += n%10;
n /= 10;
}
if(s/10 != 0){
return check(s);
}
return s;
}

Large FIbonacci Java Time Exceeded

I'm stuck on a test case.
The question requires to compute a large Fibonacci number in a given period of time.
I have passed 8 cases out of 10 and stuck on 9.
Here is my Code:
import java.util.*;
import java.math.BigInteger;
public class LastNumberofFibo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger bi = sc.nextBigInteger();
System.out.println(fib(bi));
}
public static BigInteger fib(BigInteger n) {
BigInteger val=new BigInteger("10");
int k = n.intValue();
BigInteger ans = null;
if(k == 0) {
ans = new BigInteger("0");
} else if(Math.abs(k) <= 2) {
ans = new BigInteger("1");
} else {
BigInteger km1 = new BigInteger("1");
BigInteger km2 = new BigInteger("1");
for(int i = 3; i <= Math.abs(k); ++i) {
ans = km1.add(km2);
km2 = km1;
km1 = ans;
}
}
if(k<0 && k%2==0) { ans = ans.negate(); }
return ans.mod(val);
}
}
After Submitting I get the following Time-out result.
I need help in making my code more efficient.
Feedback :
Failed case #9/10: time limit exceeded
Input:
613455
Your output:
stderr:
(Time used: 3.26/1.50, memory used: 379953152/536870912.)
Please guide me.
Yours Sincerely,
Vidit Shah
I have taken the most easy to implemement suggestions from comments and put it in code.
import java.util.*;
import java.math.BigInteger;
public class LastNumberofFibo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger bi = sc.nextBigInteger();
System.out.println(fib(bi));
}
public static BigInteger fib(BigInteger n) {
int m = 10;
BigInteger sixty = new BigInteger("60");
int k = (n.mod(sixty)).intValue();
int ans = 0;
if(k == 0) {
ans = 0;
} else if(Math.abs(k) <= 2) {
ans = 1;
} else {
int km1 = 1;
int km2 = 1;
for(int i = 3; i <= Math.abs(k); ++i) {
ans = (km1 + km2)%m;
km2 = km1;
km1 = ans;
}
}
if(k<0 && k%2==0) { ans = -ans; }
return new BigInteger("" + ans);
}
}
Try that:
public static int fibonacci(int n) {
return (int)((Math.pow((1 + Math.sqrt(5)) / 2, n) - Math.pow((1 - Math.sqrt(5)) / 2, n)) / Math.sqrt(5));
}

Java, Largest prime factor

I'm trying to solve this question:
https://www.hackerrank.com/contests/projecteuler/challenges/euler003/submissions/code/2977447
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?
Input Format
First line contains T, the number of test cases. This is followed by T lines each containing an integer N.
Output Format
For each test case, display the largest prime factor of N.
Constraints
1≤T≤10
10≤N≤1012
and my code below gets a timeout error for the fifth test (which we don't know about the actual content). any thought why did it fail the test? thanks
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
/* Author: Derek Zhu
* 1and1get2#gmail.com
* https://www.hackerrank.com/contests/projecteuler/challenges/euler003
* */
// The part of the program involving reading from STDIN and writing to STDOUT has been provided by us.
public class Solution {
public static boolean D = true;
static BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args) throws NumberFormatException,
IOException {
int numOfCases = Integer.parseInt(in.readLine());
for (int i = 0; i < numOfCases; i++){
calculateCase(Long.parseLong(in.readLine()));
}
}
private static void calculateCase(Long input) throws IOException{
if (D) System.out.println("Processing: " + input);
long largestPF = prime(input);
if (D) System.out.print("Final calculate: ");
System.out.println(largestPF);
}
private static long prime(long n){
long i = 2;
while ( n % i != 0 && i < n){
i ++;
}
if (D) System.out.println("found i: " + i);
if (i < n){
return prime(n/i);
} else {
return n;
}
}
public static int primeFactors(BigInteger number) {
BigInteger copyOfInput = number;
int lastFactor = 0;
for (int i = 2;
BigInteger.valueOf(i)
.compareTo(copyOfInput) <= 0; i++) {
if (copyOfInput.mod(BigInteger.valueOf(i))
.compareTo(BigInteger.ZERO) == 0)
{
lastFactor = i;
copyOfInput = copyOfInput
.divide(BigInteger.valueOf(i));
i--;
}
}
return lastFactor;
}
}
Thanks #ajb
as it turns out, taking another method would be much efficient.
private static long method2(long NUMBER){
long result = 0;
for(int i = 2; i < NUMBER; i++) {
if(NUMBER % i == 0 && isPrime(NUMBER / i)) {
result = NUMBER / i;
break;
}
}
return result;
}
private static boolean isPrime(long l) {
for(long num = 2, max = l / 2 ; num < max; num++) {
if(l % num == 0) {
return false;
}
}
return true;
}
complete code with comparison of time can be found here:
https://github.com/1and1get2/hackerrank/blob/master/Contests/ProjectEuler%2B/003_LargestPrimeFactor/src/Solution.java
if (NUMBER<2){
return -1;
}
int result = 0;
for (int i =2; NUMBER>i; i++ ){
if (NUMBER%i==0){
result = NUMBER / i;
if (result/1==result && result/result==1 && result%2!=0 && result%3!=0 && result%5!=0 && result%7!=0){
break;
}
}
}
return result;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int count,k=0,n=0;
long arr[]=new long[1000000];
long arr1[]=new long[1000000];
long arr2[]=new long[10000000];
for(int a0 = 0; a0 < t; a0++){
arr[a0] = in.nextLong();
}
for(int i=0;i<t;i++)
{
for(int j=2;j<=arr[i];j++)
{
if(arr[i]%j==0)
{
arr1[k]=j;
k++;
}
}
for(int l=0;l<k;l++)
{
count=0;
for(int m=1;m<=arr1[l];m++)
{
if(arr1[l]%m==0)
{
count++;
}
}
if(count==2)
{
arr2[n]=arr1[l];
n++;
}
}
Arrays.sort(arr2);
System.out.println(arr2[arr2.length-1]);
}
}
}

Check repetition of fractions of external file

I'm creating a program that has a requirement of three classes. The program reads an external text file filled with fractions, and is to return how many times each fraction is repeated. 4/2 has to be reduced to 2/1 and is +1 for the 2/1 count. I believe I am almost done, but I cannot figure out what I need to put into my compareAndIncrement() method in my FractionCounter class. It is suppose to be used to see if the newFraction passed into the function is the same as the Fraction being stored, and if so increments the counter by one and returns true (otherwise, returns false). Below are the codes for my classes.
FractionCounter
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FractionCounter {
private Fraction theFraction;
private int counter = 0;
public FractionCounter(Fraction theFraction ){
}
public boolean compareAndIncrement(Fraction newFraction){
return false;
}
public String toString(){
return "";
}
public static void main(String[] args){
ObjectList num = new ObjectList();
ObjectList den = new ObjectList();
Scanner fractionFile = null;
try{
fractionFile = new Scanner(new FileInputStream("fractions.txt"));
}
catch (FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
while (fractionFile.hasNextLine()){
String[] part = (fractionFile.nextLine().split("/"));
num.add(Integer.parseInt(part[0]));
den.add(Integer.parseInt(part[1]));
}
}
}
Fraction
public class Fraction {
private int numerator;
private int denominator;
public Fraction() {
}
public Fraction(int num, int den) {
setNumerator(num);
setDenominator(den);
}
public void setNumerator(int num) { //sets numerator
numerator = num;
}
public int getNumerator() { //gets numerator
return numerator;
}
public void setDenominator(int den) { //sets denominator
if(den == 0) {
System.out.println("Error: Denominator = 0");
System.exit(0);
} else {
denominator = den;
}
}
public int getDenominator() { //gets denominator
return denominator;
}
public boolean equals(Fraction that) {
return ((double)this.numerator/this.denominator) == ((double)that.numerator/that.denominator);
}
}
ObjectList
public class ObjectList {
private int[] fraction = new int[100];
private int numElements = 0;
public void add(int n){
fraction[numElements] = n;
numElements++;
}
public String toString(){
String retVal = "";
for (int i = 0; i < numElements; i++){
retVal += fraction[i] + ",";
}
return retVal;
}
public int indexOf(int[] input, int target) {
//returns the index of the inputed value
if(contains(input,target) == true){
for(int i = 0;i <= target;i++) {
if(input[i] == target) {
return i;
}
}
}
return -1;
}
public boolean contains(int[] input, int target) {
//is the target in the inputed array?
for(int i=0;i<input.length; i++) {
if(input[i] == target) {
return true;
}
}
return false;
}
}
Any hints or tips for what I need to do to my method would be much appreciated. I can't figure out a way to do it without using numElements and fraction variables from my ObjectList class. Thank you
I would make a Map to make the counter :
private static final Map<Fraction, Integer> counter = new HashMap<Fraction, Integer>();
and for each Fraction element read for the file I would do :
if(counter.containsKey(fraction)){
Integer count = counter.get(fraction);
count++;
counter.put(fraction, count);
} else {
counter.put(fraction, 1);
}
Moreover, I would make a static parse fonction in the Fraction class which return a Fraction instance from the line you just read. And a toString function to print it easely.

Categories