• Ayushi Jain Feb-12-2019 05:52:33 AM ( 3 months ago )

Write a program to read n numbers. The first number specified as input will be n. Next, the program should read n integer numbers.

The program should check for each number if it is prime as well as if its reverse is prime.

Display all such numbers in ascending order.

Consider below example for input and output:

Input: 7 11 12 23 19 7 113 101

Output:

7 11 101 113

My code

``````public class Prime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int temp;

int[] a = new int [x];
int[] r = new int [x];
int[]c = new int[a.length+r.length];
int[] rev = new int [x];

for(int i=0;i<x;i++){
a[i] = sc.nextInt();
rev[i]=a[i];
}

for(int i = 0; i < a.length; i++) {
while(rev[i] != 0) {
r[i] = r[i] * 10;
r[i] = r[i] + rev[i]%10;
rev[i] = rev[i]/10;
}
}

for(int i = 0; i < a.length; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if((``````
``` ```
• ``` Vikrant Srivastava Feb-12-2019 05:57:22 AM ( 3 months ago ) To eliminate duplicates , use a Set Katie George Feb-12-2019 05:58:33 AM ( 3 months ago ) Please show what you have tried, and why exactly it didn't work, in the smallest amount of code possible. We're here to help you solve a specific problem, not write your code for you. Arminder Gill Feb-12-2019 06:02:52 AM ( 3 months ago ) Try breaking down the problem into smaller chunks. I recommend making a few methods which each handle a small portion of the program. You can then test each of them individually. First make a method to check if a number is prime boolean isPrime(int i), then make method to reverse the number, int reverse(int i). Create a method boolean isReversePrime(int i) which calls both isPrime(i) and isPrime(reverse(i)), etc etc. Breaking down a problem into smaller steps may look like more work, but it makes your code much easier to read and also much easier to verify the correctness. Nageshwer Reddy Feb-12-2019 06:04:32 AM ( 3 months ago ) Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor which all ready cover. Apoorva Saxena Feb-12-2019 06:05:50 AM ( 3 months ago ) You need to use TreeSet - which will contain only distinct elements and give result in sorted form. You can refer to following code- Set<Integer> set = new TreeSet<>(); for(int i = 0; i < a.length; i++) { boolean isPrime = true; if(isPrime(a[i]) && isPrime(r[i])) set.add(a[i]); } Also create a function for checking prime numbers - private static boolean isPrime(int num) { for(int i = 2; i <= num/2; ++i) { if(num % i == 0) { return false; } } return true; } Sophia Chang Feb-12-2019 06:08:34 AM ( 3 months ago ) Here is the code for prime test using √n approach static boolean isPrime(int n){ //corner case if (n <= 1) return false; if (n <= 3) return true; //middle 5 number if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } Use can use set for remove duplicate element Lucky Negi Feb-12-2019 06:10:10 AM ( 3 months ago ) You can use Stream.distinct() in Java 8 just pass your array to an array list and remove its duplicates by using .distinct() import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; //list with duplicates List<Integer> list = new ArrayList<>( Arrays.asList(3, 10, 3, 3, 4, 5, 5)); //new list without duplicates List<Integer> newList = list.stream() .distinct() .collect(Collectors.toList()); ```
``` ```
``` Please login ```
``` ```
``` Similar Discussion Software testing tools for testing web application [closed] Posted By: Karlie Kloss Bugs & Fixes May-10-2019 04:34:43 AM ( 2 weeks ago ) 0 How to vertically center a div for all browsers? Posted By: Rahul Chaudhary Bugs & Fixes May-09-2019 07:49:12 AM ( 2 weeks ago ) 0 “php: command not found” after changing PHP system files in OS X Posted By: Alice Davidson Bugs & Fixes May-08-2019 07:23:07 AM ( 2 weeks ago ) 0 Use PHP to convert Texas State Plane to decimal Posted By: Rukhsar Fatima Bugs & Fixes May-08-2019 07:21:42 AM ( 2 weeks ago ) 0 Recommended For You Jobs Internships Services Projects Courses Trainings Workshops Addmissions Study Abroad Question Bank Pre-Assessment Affiliate Marketing Webinars var owl = \$("#jobseeker-slide, #similar-courses-slider,#similar-admission-slider,#study-abroad-slider,#similar-training-slider,#similar-workshop-slider,#similar-projects-slider"); owl.owlCarousel({ itemsCustom : [ [0, 1], [450, 1], [600, 1], [700, 1], [1024, 2], [1200, 2], [1400, 2], [1600, 3] ],navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], navigation:true, loop:true, autoPlay: true, autoplayTimeout: 100, stopOnHover : true, autoHeight:true }); var owl2 = \$("#courses-slide,#train-slide,#wshop-slide,#intern-slide,#sjobs-slide,#sprojects-slide,#services-slider,#similar-internship-slider,#similar-shortjobs-slider"); owl2.owlCarousel({ itemsCustom : [ [0, 1], [450, 1], [600, 1], [700, 1], [1024, 4], [1200, 4], [1400, 4], [1600, 4] ], navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], navigation:true, loop:true, autoPlay: false, autoplayTimeout: 100, stopOnHover : true }); ```
``` ```
``` ```
``` ```
``` ```
``` TuteeHUBBeta A Gateway of Opportunities Sign In Alert Please Sign In To Continue. TuteeHUBBeta A Gateway of Opportunities TuteeHUB is a technology driven cloud platform to "Learn, Work & Earn" through learning products, self-development services, employment and remote work options with integrated marketing & promotions opportunities. 011-42427761 info[@]tuteehub[.]com Social Connect Help & Support Forum Help Desk FAQ Insights Career News Articles Feeds Our Services Pre Assessment Exclusive Services Courses & Admissions Trainings & Workshops Jobs Internships Projects Services Affiliate Marketing Webinars Our Community Scholars Corporates Consultants Campus Institutes Affiliates App Download Latest Article EPFO Associate Recruitmen... May 24, 2019 The Employees’ Provident... Indian Institute of Mass ... May 24, 2019 Indian Institute of Mass Commu... Personal Assistant (Patna... May 23, 2019 Patna High Court, (Patna,Bihar... Newsletter App Download        Social Connect About Us How It Works Privacy Policy Terms & Conditions Contact Us   Copyright © 2018 TuteeHUB. All Right Reserved. TuteeHUBBeta A Gateway of Opportunities Plan Upgrade Alert! Please Upgrade Your Plan! GET LATEST OPENINGS IN YOUR INBOX Jobs | Project | Services | Internship | Courses | Career News /* alert(position); */ var isshow =sessionStorage.getItem('isshow'); /* if (isshow== null) { sessionStorage.setItem('isshow', 1); setTimeout(function(){\$('#get-response-modal').modal();},1500); } */ /* \$(document.ready(function(){ if (\$.cookie('test_status') != '1') { \$('#get-response-modal').modal(); \$.cookie('test_status', '1', { expires: 6000}); } }) */ var position=\$('footer').offset().top; // \$(window).scroll(function(){ // var ws=\$(window).scrollTop(); // var newp=position+40; // if(ws>position && ws<newp) // { // sessionStorage.setItem('isshow', 'null'); // \$('#get-response-modal').modal(); // }}) function checkAccess() { /* \$('#accessMessage').html('Please Upgrade Your Plan'); */ \$('#accessModule').modal(); } \$('i[data-toggle="popover"]').popover(); \$(".left-side-bar").niceScroll({ cursorcolor:"rgba(0,0,0,0.5)", cursorwidth:"8px" }); function INAuth(){ IN.User.authorize(function(){ InLoad(); }); } // Setup an event listener to make an API call once auth is complete function InLoad() { IN.Event.on(IN, "auth", InProfileData); } // Handle the successful return from the API call function InSuccess(profile) { \$('.loaders').show(); var email = profile.values[0].emailAddress; var fname = profile.values[0].firstName; var lname = profile.values[0].lastName; var siteurl = \$('meta[name=siteurl]').attr('content'); var CSRF_TOKEN = \$('meta[name=_token]').attr('content'); if(email != '' && fname != '') { \$.ajax({ url: siteurl+'/user/register', dataType: "json", type: "POST", data: { '_token': CSRF_TOKEN, 'email': email, 'fname': fname, 'lname': lname, 'registerVia': 'socialMedia', 'socialMediaName': 'linkedin' }, success: function(response) { \$('.loaders').hide(); if(response == 'IsLoggedin') { window.location = siteurl+'/user/dashboard'; } } }); } else { InError('error'); } \$('.InloginButton').remove(); InLogout(); } function InLogout() { // if (IN.User.isAuthorized()) // { // IN.User.logout(); // } } // Handle an error response from the API call function InError(error) { \$('.InloginButton').remove(); InLogout(); alert('Something Went wrong, Please Try another Login/Register Option'); } // Use the API call wrapper to request the member's basic profile data function InProfileData() { IN.API.Profile("me").fields(["firstName","lastName", "emailAddress", "phone-numbers"]).result(InSuccess).error(InError); } function FBAuth(){ FB.login(checkLoginState, {scope: 'email,public_profile', return_scopes: true}); } function checkLoginState() { FB.getLoginStatus(function(response) { statusChangeCallback(response); }); } function statusChangeCallback(response) { if (response.status === 'connected') { FBProfileData(); } else {} } function FBProfileData() { FB.api('/me?fields=id,name,email', function(response) { var name = response.name; var username = name.split(' '); var firstName = username[0]; var lastName = username[username.length - 1]; \$('.loaders').show(); var email = response.email; var fname = firstName; var lname = lastName; var siteurl = \$('meta[name=siteurl]').attr('content'); var CSRF_TOKEN = \$('meta[name=_token]').attr('content'); if(email != '' && fname != '') { \$.ajax({ url: siteurl+'/user/register', dataType: "json", type: "POST", data: { '_token': CSRF_TOKEN, 'email': email, 'fname': fname, 'lname': lname, 'registerVia': 'socialMedia', 'socialMediaName': 'facebook' }, success: function(response) { \$('.loaders').hide(); if(response == 'IsLoggedin') { window.location = siteurl+'/user/dashboard'; } } }); } }); } function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); var name = profile.getName(); var username = name.split(' '); var firstName = username[0]; var lastName = username[username.length - 1]; \$('.loaders').show(); var email = profile.getEmail(); var fname = firstName; var lname = lastName; var siteurl = \$('meta[name=siteurl]').attr('content'); var CSRF_TOKEN = \$('meta[name=_token]').attr('content'); if(email != '' && fname != '') { \$.ajax({ url: siteurl+'/user/register', dataType: "json", type: "POST", data: { '_token': CSRF_TOKEN, 'email': email, 'fname': fname, 'lname': lname, 'registerVia': 'socialMedia', 'socialMediaName': 'google' }, success: function(response) { \$('.loaders').hide(); if(response == 'IsLoggedin') { window.location = siteurl+'/user/dashboard'; } } }); } } function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element'); } if (window.location.href.indexOf("user/login") <= -1){ window.fbAsyncInit = function(){ FB.init({ appId:'1123210154481974', status:true, cookie:true, xfbml:true}); FB.getLoginStatus(function(response){ if (response.status != "unknown") { show_login_status("Facebook", true); }else{ show_login_status("Facebook", false); } }); }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); } /*<![CDATA[*/window.zE||(function(e,t,s){var n=window.zE=window.zEmbed=function(){n._.push(arguments)}, a=n.s=e.createElement(t),r=e.getElementsByTagName(t)[0];n.set=function(e){ n.set._.push(e)},n._=[],n.set._=[],a.async=true,a.setAttribute("charset","utf-8"), a.src="https://static.zdassets.com/ekr/asset_composer.js?key="+s, n.t=+new Date,a.type="text/javascript",r.parentNode.insertBefore(a,r)})(document,"script","0506877a-b916-4374-9217-21354c508ed8");/*]]>*/ ```