I took the following program from here,
import java.io.*;
import java.math.*;
class GFG {
/* Iterative Function to calculate
// (a^n)%p in O(logy) */
static int power(int a,int n, int p)
{
// Initialize result
int res = 1;
// Update 'a' if 'a' >= p
a = a % p;
while (n > 0)
{
// If n is odd, multiply 'a' with result
if ((n & 1) == 1)
res = (res * a) % p;
// n must be even now
n = n >> 1; // n = n/2
a = (a * a) % p;
}
return res;
}
// If n is prime, then always returns true,
// If n is composite than returns false with
// high probability Higher value of k increases
// probability of correct result.
static boolean isPrime(int n, int k)
{
// Corner cases
if (n <= 1 || n == 4) return false;
if (n <= 3) return true;
// Try k times
while (k > 0)
{
// Pick a random number in [2..n-2]
// Above corner cases make sure that n > 4
int a = 2 + (int)(Math.random() % (n - 4));
// Fermat's little theorem
if (power(a, n - 1, n) != 1)
return false;
k--;
}
return true;
}
// Driver Program
public static void main(String args[])
{
int k = 3;
if(isPrime(11, k))
System.out.println(" true");
else
System.out.println(" false");
if(isPrime(15, k))
System.out.println(" true");
else
System.out.println(" false");
}
}
and converted into a Python program:
#############################
# random number generation
#############################
m = 4294967296
a = 1664525
c = 1013904223
seed = 1
def NextInt():
global seed
seed = (((a * seed + c) % m))
return seed
def NextInt2(min, max):
temp = NextInt()
ddd = temp / m
return int((max - min) * ddd + min)
def NextDouble():
temp = NextInt()
return temp / m
def NextDouble2(min, max):
temp = NextInt()
fraction = temp / m
return (max - min) * fraction + min
#######################################
# Fermet's method of primality test
#######################################
def Power(a, n, p):
res = 1;
a = a % p;
while (n > 0):
if ((n and 1) == 1):
res = (res * a) % p;
n = n / 2;
a = (a * a) % p;
return res;
def IsPrime(n, k):
if (n <= 1 or n == 4):
return False;
if (n <= 3):
return True;
while (k > 0):
a = 2 + NextInt() % (n - 4);
if (Power(a, n - 1, n) != 1):
return False;
k = k-1;
return True;
#####################
# Main Program
#####################
k = 3;
if(IsPrime(11, k)):
print(" true");
else:
print(" false");
if(IsPrime(15, k)):
print(" true");
else:
print(" false");
This Python program is always returning False.
Why?
Related
We are given a static graph of N nodes, where we have edges as given below:
1. node-1 to node-i (for all 2 <= i <= N) of weight N + 1.
2. node-x to node-y (for all 2 <= x,y <= N) of weight 1, if and only if x divides y OR y divides x.
We are given Q queries of type(u, v) and we need to find shortest path between nodes u and v.
Constraints :
T <= 10^5 // number of test cases
N <= 2 * 10^5 // number of nodes
Q <= 2 * 10^5 // number of queries
u,v <= N
Approach : Almost constant time - O(1).
private int gcd(int x, int y) {
if(x % y == 0) return y;
return gcd(y, x % y);
}
private int lcm(int x, int y) {
return (x * y) / gcd(x, y);
}
private int[] shortest_path(int N, int Q, int[][] queries) {
int[] result = new int[Q];
int[] smallestDivisor = new int[N + 1];
for(int i = 2; i <= N; i++) {
if(smallestDivisor[i] == 0) {
int f = 1;
while(i * f <= N) {
if(smallestDivisor[i * f] == 0)
smallestDivisor[i*f] = i;
f += 1;
}
}
}
for(int i = 0; i < Q; i++) {
int u = queries[i][0];
int v = queries[i][1];
int LCM = lcm(u, v);
int GCD = gcd(u, v);
int smallestDivisorOfU = smallestDivisor[u];
int smallestDivisorOfV = smallestDivisor[v];
if(u == v)
result[i] = 0; // if nodes are same
else if(u == 1 || v == 1)
result[i] = N + 1; // if any of the node is '1'
else if(u % v == 0 || v % u == 0)
result[i] = 1; // if nodes are divisible
else if(GCD != 1 || LCM <= N)
result[i] = 2; // if gcd != 1 || lcm exists thus we can go as: 'x' --> gcd(x, y)/lcm(x,y) --> 'y' : 2 distance
else if(Math.min(smallestDivisorOfU * v, smallestDivisorOfV * u) <= N)
result[i] = 3;
else
result[i] = 2 * (N + 1); // we have to go via '1' node
}
return result;
}
Will this approach work for every test case?
Add GCD claculation before LCM to provide path A => GCD(A,B) => B (done)
When LCM checking fails, make factorization of values. If they are prime, move through "1" node. Otherwise check
if (min(SmallestDivisorOfA * B , SmallestDivisorOfB * A) <= N)
result[i] = 3;
Example: 7=>14=>2=>6
I'm trying to make an efficient function that's described in the title of this question. Here is what I have tried, but I'm sure their is a better way. I'm using Java 8
Question: Is their a better way to implement this function that is more efficient?
private static double nearestMod(double n) {
// Check if n already satisfies the condition
if (32 % n == 0) {
return n;
}
// Check if the solution can't be reasonably obtained
if (n > 32) {
return -1;
}
double increment;
int numsAfterDecimalPoint = String.valueOf(n).split("\\.")[1].length();
if (n % 1 == 0) {
// If n is a whole number
increment = 10;
} else {
increment = 1d / Math.pow(10, numsAfterDecimalPoint - 1);
}
double result = Double.MAX_VALUE;
double multiplier = increment == 10 ? 1 : Math.pow(10, numsAfterDecimalPoint);
for (double i = n - increment * multiplier; i < n + increment * multiplier; i += increment / 10d) {
double check = 32 / i;
if (Math.abs(Math.round(check) - check) < increment / 10d && Math.abs(i - n) < Math.abs(result - n)) {
result = i;
}
}
return result;
}
Example:
nearestMod(0.26) should return 0.25
I am looking for a Method that removes all 9's from an Integer:
public int noNine(int i){
int res = 0;
return res;
}
Examples:
noNine(0)->0
noNine(1991)->11
noNine(99)->0
noNine(19293949)->1234
And so on.
No Strings are allowed and no external Methods.
Can you help me?
Thanks!
Eddie Texas
int removeNine(int n)
{
int result = 0;
int mul = 1;
while(n > 0)
{
//check if current digit is 9. if 9 then do nothing
if(n % 10 == 9)
{
n = n / 10;
continue;
}
else
{
//if not 9 then add this to result after multiplying by current mul
result += mul * (n % 10);
//update mul so that the next digit is added according to power of 10
mul = mul * 10;
}
n = n / 10;
}
return result;
}
You could solve this problem in multiple ways
Using a for loop to loop through each character
Using recursion
I'm going to elaborate on the second technique:
Using this technique, you could solve the problem using integers or strings. I'm going to be using intergers as you said it is a required aspect:
Get the last digit using % 10
Remove it if it is a 9
Recursively check each digit (*Remember to have a base case!)
Return final value
public int noNine(int i){
if(i < 10){
if(i == 9)
return 0;
else
return i;
}
int lastDigit = i % 10;
if(lastDigit == 9)
return noNine(i / 10);
else
return noNine(i / 10)*10+lastDigit;
}
The key takeaway here is that: n % 10 = last digit of n and n / 10 = all previous digits of n. This happens due to integer division in Java!
You could do it like this:
public int removeNines(int n) {
int returnValue = 0, multiplier = 1;
while (n > 0) {
if (n%10 != 9) {
returnValue += (n%10) * multiplier;
multiplier *= 10;
}
n /= 10;
}
return returnValue;
}
This loops through all digits and if it is not a 9 it adds it to the output. Tested here and works
Here's my version written in a slightly different manner than ritratt just in case you are not understanding his version:
public int noNines(int num) {
int multiplier = 0;
int result = 0;
while (num > 0) {
int digit = num % 10;
System.out.println("digit=" + digit);
if (digit == 9) {
//ignore
} else {
System.out.println("Adding " + (digit * (int)Math.pow(10, multiplier)));
result += digit * (int)Math.pow(10, multiplier);
multiplier++;
}
num = num / 10;
}
return result;
}
I left console output so you can see the method in action.
I am working on an interview question which I was asked in which I was supposed to write a program to find the largest palindrome from product of two three digit numbers.
Here is the question
I came up with this brute force approach which starts from bottom.
public class LargestPalindromeQuestion {
public static void main(String[] args) {
int value = 0;
for (int i = 100; i <= 999; i++) {
for (int j = i; j <= 999; j++) {
int value1 = i * j;
if (isPalindrome(value1) && value < value1) {
value = value1;
}
}
}
System.out.println(value);
}
private static boolean isPalindrome(final int product) {
int p = product;
int reverse = 0;
while (p != 0) {
reverse *= 10;
reverse += p % 10;
p /= 10;
}
return reverse == product;
}
}
They asked me what are the optimizations I can do in this program? I mentioned that we can try pruning the search space and optimize checking step for each item in the search space but then I am confuse how would I make this work in my above solution?
What are the optimizations we can do in this program? Right now it is executing 810000 steps to find the largest palindrome.
What is the least number of steps we can execute to find the largest palindrome in two three digit numbers?
The program looks very good to me. I would make the i loop count from 999 down to 100, and I would only check j values that would actually give a larger product than the current maximum.
This program is able to finish surprisingly soon, at i == 952 to be precise. The mathematical reason for this is that once the solution 906609 (993 * 913) is found, it will no longer be possible to find a larger palindrome where the larger factor is less than the square-root of 906609, which is 952.160....
public static void main(String[] args) {
int value = 0;
for (int i = 999; i >= 100; i--) {
int r = value / i;
if (r >= i) {
System.out.println("We broke at i = " + i);
break;
}
for (int j = i; j > r; j--) {
int value1 = i * j;
if (isPalindrome(value1)) {
value = value1;
break;
}
}
}
System.out.println(value);
}
One pretty simple way of optimizing this would be to simply start with the highest 3-digit numbers instead of the smallest. Since the solution will most likely be closer to the pair (999 , 999) than to (100 , 100).
One useful mechanism to prune the search tree is to notice that the highest digit of the product a * b doesn't change often. E.g.
a = 111; b = 112 a*b = 12432
; b = 113 a*b = 12543
; b = 114 a*b = 12654
; ...
; b = 180 a*b = 19980
; b = 181 a*b = 20091 = (19980 + a)
Thus, for all the values in between (a = 111, a < b < 181), one already knows the MSB, which must equal to the LSB or (a % 10) * (b % 10) % 10 == MSB.
e.g.
LSB = 1 --> a % 10 == 1, b % 10 == 1
OR a % 10 == 3, b % 10 == 7
OR a % 10 == 7, b % 10 == 3
OR a % 10 == 9, b % 10 == 9
Most of the time there's either none, or just one candidate in set 'b' to be checked for any pair MSB, a % 10.
The least number of steps I could get to is 375. Consider multiplying the three-digit number, a1a2a3, by the three-digit number, b1b2b3:
JavaScript code:
var modHash = new Array(10);
var iterations = 0;
for (var i=1; i<10; i++){
modHash[i] = {0: [0]}
for (var j=1; j<10; j++){
iterations ++;
var r = i * j % 10;
if (modHash[i][r])
modHash[i][r].push(j);
else
modHash[i][r] = [j];
}
}
var highest = 0;
function multiples(x,y,carry,mod){
for (var i in modHash[x]){
var m = (10 + mod - i - carry) % 10;
if (modHash[y][m]){
for (var j in modHash[x][i]){
for (var k in modHash[y][m]){
iterations ++;
var palindrome = num(9,modHash[y][m][k],x,9,modHash[x][i][k],y);
if (x == 3 && mod == 0){
console.log(x + " * " + modHash[x][i][j] + " + "
+ y + " * " + modHash[y][m][k] + ": " + palindrome);
}
var str = String(palindrome);
if (str == str.split("").reverse().join("") && palindrome > highest){
highest = palindrome;
}
}
}
}
}
}
function num(a1,a2,a3,b1,b2,b3){
return (100*a1 + 10*a2 + a3)
* (100*b1 + 10*b2 + b3);
}
var a3b3s = [[7,7,4],[9,1,0],[3,3,0]];
for (var i in a3b3s){
for (var mod=0; mod<10; mod++){
var x = a3b3s[i][0],
y = a3b3s[i][1],
carry = a3b3s[i][2];
multiples(x,y,carry,mod);
}
}
console.log(highest);
console.log("iterations: " + iterations);
Output:
3 * 0 + 3 * 0: 815409
3 * 7 + 3 * 3: 907809
3 * 4 + 3 * 6: 908109
3 * 1 + 3 * 9: 906609
3 * 8 + 3 * 2: 907309
3 * 5 + 3 * 5: 908209
3 * 2 + 3 * 8: 907309
3 * 9 + 3 * 1: 906609
3 * 6 + 3 * 4: 908109
3 * 3 + 3 * 7: 907809
906609
iterations: 375
First optimize isPalindrome by seperating 6 digits as 3 digits. i.e. N = ABCDEF => a = ABC = N/1000, b = DEF = N%1000; Then reverse b and return a==reversed_b;
Secondly while producing palindromes loop through till max_palindrome_so_far/999 which is the minimum value that you would use. max_palindrome_so_far is initially equals N.
public class Solution {
public static boolean isPalindrome(int n){
int a = n/1000;
int b = n%1000;
int d, r = 0, i = 3;
while(i-- > 0){
d = b%10;
r = r*10 + d;
b = b/10;
}
if (a == r)
return true;
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
int r=0, m=n;
int i,j;
for(i = 999;i>=100;i--){
for(j = 999;j>=m/999;j--){
if (i*j < n && i*j > 100000 && isPalindrome(i*j)){
r = Math.max(i*j, r);
m = r;
}
}
}
// System.out.println(i + " * " + j + " = " + i*j);
System.out.println(r);
}
}
}
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
My solution:
public class Prime_Number {
public static boolean isPrime(long n) {
if ((n > 2 && n % 2 == 0) || (n > 3 && n % 3 == 0) || (n > 5 && n % 5 == 0) || n == 0 || n == 1) {
return false;
}
return true;
}
public static void main(String[] args) {
int count = 0;
int prime = 0;
while (prime <= 10001) {
if (isPrime(count) == true) {
prime++;
if (prime == 10001) {
System.out.println(count + " is a prime number" + "(" + prime + ")");
}
}
count++;
}
}
}
But it does not give a correct answer. Please help me to upgrade my code. For instance, program defines a 91 as a prime number, but it is not a prime number. How to improve it?
You need to test the number against every prime less than its square root to ensure it is prime.
You're only testing against 2,3 and 5.
Because storing all the primes is not always space-feasable, a common technique is to test for 2, and then test all odd numbers starting at 3. This requires a loop.
consider:
boolean isPrime(long n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
if (n < 9) return true;
if (n % 3 == 0) return false;
long max = (long)(Math.sqrt(n + 0.0)) + 1;
for (int i = 5; i <= max; i += 6) {
if (n % i == 0) return false;
if (n % (i + 2) == 0) return false;
}
return true;
}
A number p is prime if it only divides by itself and 1. You are checking only for divison by 2, 3 and 5. This is not enough. Check for every number till p / 2, or better till sqrt(p).
The following solution checks only the odd numbers to be prime, but it counts 2 as prime from the beginning:
public class A {
static int N = 10001;
private static boolean isOddPrime(long x) {
for ( int i = 3 ; i*i <= x ; i+=2 ) {
if ( x % i == 0 ) {
return false;
}
}
return true;
}
public static void main(String[] args) throws Exception {
long start = System.nanoTime();
int x;
int i = 2; // 3 is the 2nd prime number
for ( x = 3 ; ; x+=2 ) {
if ( isOddPrime(x) ) {
if ( i == N )
break;
i++;
}
}
System.out.println(x);
long stop = System.nanoTime();
System.out.println("Time: " + (stop - start) / 1000000 + " ms");
}
}
Output:
104743
Time: 61 ms
I would comment, but I just joined.
You don't have to check every number between 1 and a numbers square root for potential divisors, you just have to check all previous primes (assuming you start at 1 and iterate up), as any other divisor that is not prime will itself be divisible by a prime of a lower value. the higher the number of primes, the more checks against non prime numbers this saves. the example is in C# but that's more to demonstrate the concept.
//store found primes here, for checking subsequent primes
private static List<long> Primes;
private static bool IsPrime(long number)
{
//no number will have a larger divisor withou some smaller divisor
var maxPrime = Math.Sqrt(number);
// takes the list of primes less than the square root and
// checks to see if all of that list is not evenly
// divisible into {number}
var isPrime = Primes
.TakeWhile(prime => !(prime > maxPrime))
.All(prime => number % prime != 0);
if (isPrime)
Primes.Add(number);
return isPrime;
}
private static long GetNthPrime(int n)
{
//reset primes list to prevent persistence
Primes = new List<long> { 2, 3, 5, 7 };
//prime in starting set
if (Primes.Count >= n)
{
return Primes[n - 1];
}
//iterate by 6 to avoid all divisiors of 2 and 3
// (also have to check i + 2 for this to work)
// similar to incrementing by 2 but skips every third increment
// starting with the second, as that is divisible by 3
for (long i = 11; i < long.MaxValue; i += 6)
{
// only check count if is prime
if ((IsPrime(i) && Primes.Count >= n) || (IsPrime(i + 2) && Primes.Count >= n))
{
break;
};
}
//return end of list
return Primes[n - 1];
}